只支持单线程,只能接收一个请求
我想加以改进,让它可以接收多个请求
注释我就不加了
可以参考用winsock版,好像java的更简单
?
import java.io.*;
import java.net.*;
import java.util.*;
public class WebServer{
? public static void main(String []args)throws Exception{
??? String requestMessageLine;
??? String fileName;
??? ServerSocket listenSocket=new ServerSocket(80);
??? Socket connectSocket=listenSocket.accept();
??? BufferedReader inFormClient=new BufferedReader(new
??????? InputStreamReader(connectSocket.getInputStream()));
??? DataOutputStream outToClient=new
??????? DataOutputStream(connectSocket.getOutputStream());
??? requestMessageLine=inFormClient.readLine();
??? StringTokenizer tokenizedLine=new StringTokenizer(requestMessageLine);
??? if(tokenizedLine.nextToken().equals("GET")){
????? fileName=tokenizedLine.nextToken();
????? if(fileName.startsWith("/")==true){
??????? fileName=fileName.substring(1);
????? }
????? String filePath=new String("D:\\Java\\httpserver\\classes\\");
????? File file=new File(filePath+ fileName);
????? int numOfBytes=(int)file.length();
????? FileInputStream inFile=new FileInputStream(filePath+fileName);
????? byte []fileInBytes=new byte[numOfBytes];
????? inFile.read(fileInBytes);
????? outToClient.writeBytes("HTTP/1.0 200 Document Follows\r\n");
????? if(fileName.endsWith(".jpg")){
???????? outToClient.writeBytes("Conten-Type: image/jpeg\r\n");
????? }
????? else if(fileName.endsWith(".gif")){
???????? outToClient.writeBytes("Conten-Type: image/gif\r\n");
????? }
????? outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
????? outToClient.writeBytes("\r\n");
????? outToClient.write(fileInBytes,0,numOfBytes);
????? connectSocket.close();
??? }
??? else{
????? System.out.println("No support for other request except GET!");
??? }
? }
}