1. 程式人生 > >JAVA編寫的一個簡單的Socket實現的HTTP響應伺服器進階版

JAVA編寫的一個簡單的Socket實現的HTTP響應伺服器進階版

1、首先建立ServerSocket監聽8000埠,等待瀏覽器的連線。

public class HttpServer {

	//WEB_ROOT該伺服器的根目錄,這個目錄可以自己定義,主要是伺服器響應的檔案所在目錄
	public static final String WEB_ROOT = System.getProperty("user.dir")+File.separator+"webroot";
	
	public static void main(String[] args) {
		HttpServer server = new HttpServer();
		System.out.println("WEB_ROOT:"+WEB_ROOT);
		server.await();
	}
	public void await(){
		ServerSocket serverSocket = null;
		int port = 8080;
		try {
			serverSocket = new ServerSocket(port,1,InetAddress.getByName("127.0.0.1"));
			System.out.println("等待來自瀏覽器的連線...");
			while(true){
		try {
			Socket socket = null;
			InputStream input = null;
			OutputStream output = null;
			socket = serverSocket.accept();
			input  = socket.getInputStream();
			output = socket.getOutputStream();
			//封裝request請求
			Request request = new Request(input);
			request.parse();
			//封裝response物件
			Response response = new Response(output);
			response.setRequest(request);
			response.sendStaticResource();
			socket.close();
			} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
}
可以看到,瀏覽器傳送過來的請求資訊是通過socket.getInputStream();得到,並將其封裝到Request中,讓Request去處理請求資訊。

2、請求物件Request

public class Request {
	
	//輸入流
	private InputStream input;
	
	private String uri;
	public Request(InputStream inputStream){
		this.input = inputStream;
	}
	
	public InputStream getInput() {
		return input;
	}
	public void setInput(InputStream input) {
		this.input = input;
	}
	public String getUri() {
		return uri;
	}
	public void setUri(String uri) {
		this.uri = uri;
	}
	
	//從套接字中讀取字元資訊
	public void parse(){
		
			StringBuffer request = new StringBuffer(2048);
			int i = 0;
			byte[] buffer = new byte[2048];
			
			try {
				i = input.read(buffer);
			} catch (IOException e) {
				e.printStackTrace();
				i = -1;
			}
			for(int j = 0;j<i;j++){
				request.append((char)(buffer[j]));
			}
			System.out.println(request.toString());
			uri = parseUri(request.toString());
			}
	//擷取請求的url
	private String parseUri(String requestString){
		
		int index1 = 0;
		int index2 = 0;
		index1 = requestString.indexOf(' ');
		if(index1!=-1){
			index2 = requestString.indexOf(' ',index1+1);
			if(index2>index1){
				return requestString.substring(index1+1,index2);
			}
		}
		return null;
	}
}

伺服器處理完得到響應資料在socket.getOutputStream();封裝到Response

3、Response

public class Response {
	
	private static final int BUFFER_SIZE = 1024;
	Request request;
	OutputStream output;
	public Response(OutputStream output){
		this.output = output;
	}
	
	public void sendStaticResource() throws IOException{
		
		byte[] bytes = new byte[BUFFER_SIZE];
		FileInputStream fis = null;
		
		File file = new File(HttpServer.WEB_ROOT,request.getUri());
		if(file.exists()){
			try {
				fis = new FileInputStream(file);
				int ch = fis.read(bytes,0,BUFFER_SIZE);
				while(ch != -1){
					output.write(bytes,0,ch);
					ch = fis.read(bytes,0,BUFFER_SIZE);
				}
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}catch(IOException e){
				e.printStackTrace();
			}finally{
				if(fis !=null){
					fis.close();
				}
			}
			
		}else{
			//找不到檔案
			  String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
	          "Content-Type: text/html\r\n" +
	          "Content-Length: 23\r\n" +
	          "\r\n" +
	          "<h1>File Not Found</h1>";
			  try {
				output.write(errorMessage.getBytes());
				output.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public Request getRequest() {
		return request;
	}
	public void setRequest(Request request) {
		this.request = request;
	}
	public OutputStream getOutput() {
		return output;
	}
	public void setOutput(OutputStream output) {
		this.output = output;
	}
	public static int getBUFFER_SIZE() {
		return BUFFER_SIZE;
	}
}