`

A simple Http server implemented in Java

    博客分类:
  • J2SE
阅读更多
转载:http://hi.baidu.com/triceratops/blog
import java.io.*;
import java.net.*;

public class HttpServer{
private ServerSocket server;

public void startService(int port) throws IOException{
       System.out.println("service started...");
       server = new ServerSocket(port);
       while (true)
         new ServiceThread(server.accept()).start();
}


public static void main(String[] args) throws Exception{
   if(args.length!=1){
    System.out.println("Usage: java HttpServer [port]");
    System.exit(1);
   }
   new HttpServer().startService(Integer.parseInt(args[0]));
}
}


public class ServiceThread extends Thread{
private Socket serverEndPoint;
private InputStream in;
private OutputStream out;
private byte[] fileBytes;
private String threadId;
private static int id = 0;

ServiceThread(Socket serverEndPoint){
this.serverEndPoint = serverEndPoint; 
   threadId = "[No."+id+++"]";
}

private void parseHttpRequest() throws IOException{
   System.out.println(this+"=========================");
   in = serverEndPoint.getInputStream();
   BufferedReader br = new BufferedReader(new InputStreamReader(in));
   String header="";
   String fileName;
   if(br.ready())
    header = br.readLine();
   System.out.println(this+header);
   fileName = header.split(" ")[1];
   if(fileName.startsWith("/"))
    fileName = fileName.substring(1);
   if(fileName.indexOf("?")!=-1)
    fileName = fileName.substring(0,fileName.indexOf("?"));
   if(fileName.length() == 0)
    fileName = "index.html";
   fileName = fileName.replaceAll("%20"," ");
   System.out.println(this+"========================="); 
   serverEndPoint.shutdownInput();
   buildHttpResponse(getRequestedFile(fileName));
}

private boolean getRequestedFile(String fileName) throws IOException{
   File file = new File(fileName);
   if(!file.exists()||file.isDirectory())
    return false;
   FileInputStream fis = new FileInputStream(file);
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   byte[] buf = new byte[1024];
   int i;
   while((i=fis.read(buf))!=-1)
    baos.write(buf,0,i);
   fileBytes = baos.toByteArray();
  
   return true;
}

private void buildHttpResponse(boolean fileExist) throws IOException{
   out = serverEndPoint.getOutputStream();
   DataOutputStream dos = new DataOutputStream(out);
   if(fileExist){
    dos.writeBytes("HTTP/1.0 200 Document Follows\r\n"); 
    dos.writeBytes("\r\n"); 
    dos.write(fileBytes);
   }
   else{
    dos.writeBytes("HTTP/1.0 404 Document Follows\r\n"); 
    dos.writeBytes("\r\n"); 
   }
   serverEndPoint.shutdownOutput();
}

public void run(){
   try{
    parseHttpRequest();
   }
   catch(Exception e){
    System.out.println(this);
    e.printStackTrace();
   }
}

public String toString(){
   return threadId; 
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics