http\1.0简单服务器

import java.io.*;
import java.net.*;
import java.util.*;


public class Server {
public static void main(String[] args) {
//String UrlLeft_3409 = "E:\\123";
String UrlLeft = null;
if(args.length == 1){


UrlLeft = args[0];
}
else{
System.out.println("路径有错误");
System.exit(0);
}
try {


ServerSocket ss = new ServerSocket(8000);


while(true){
Socket s = ss.accept();
//System.out.println("error");
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintStream pw = new PrintStream(s.getOutputStream());
   String re = br.readLine();
   StringTokenizer st = new StringTokenizer(re," ");
   st.nextToken();
   String UrlRight = st.nextToken();
   String Url = UrlLeft + UrlRight;
   
   System.out.println("***********"+Url);
   System.out.println("***********  Left"+UrlLeft);
   System.out.println("***********  Right"+UrlRight);
   
   if(UrlRight.endsWith("html")){
   createcontent(Url,"html",pw);
   }
   else if(UrlRight.endsWith("htm")){
   createcontent(Url,"htm",pw);
   }
   else if(UrlRight.contains("jpg")||UrlRight.contains("gif")){
    createjpg(Url,pw);  
   }
   else{
    createnotfound(pw);
   }
pw.close();
br.close();
s.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String createcontent(String Url,String category,PrintStream pw){

BufferedReader fin;
try {
fin = new BufferedReader(new FileReader(new File(Url)));

   String temp = "";
   String content = ""; 
   while((temp = fin.readLine())!=null){
    content+=temp;    
   }
pw.println("HTTP/1.0 200 OK");
pw.println("Content-Type: text/" + category);
pw.println("");
pw.println(content);
//System.out.println(content);
pw.flush();
  
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
createnotfound(pw);
}
catch (IOException f){
System.out.print("io异常");
}
return null;
}
public static String createjpg (String Url,PrintStream pw){
try{
FileInputStream fs = new FileInputStream(Url);
    byte[] picture = new byte[fs.available()];
    fs.read(picture);
    pw.println("HTTP/1.0 200 OK");
pw.println("Content-Type: application/ocet-stream");
pw.println("");
pw.write(picture);
pw.flush();  
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String createnotfound (PrintStream pw){
//System.out.println("111111");
String notfound = "<html><head><title>Not Found</title></head><body><h1>Error 404-file not found</h1></body></html>";
// pw.println("HTTP/1.0 404 no found");
// pw.println("Content-Type: text/" + category);
// pw.println("");
pw.print(notfound);
//System.out.println(notfound);
pw.flush();
//e.printStackTrace();
return null;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值