模拟Tomcat

请求头: GET /aaa/index.html HTTP/1.1 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*Accept-Language: zh-cnUA-CPU: x86Accept-Encoding: gzip, deflateUser-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; CIBA) Host: localhost Connection: Keep-AliveCookie: count=john_123      响应头: HTTP/1.1 200 OK Server:Apache-Coyote/1.1Content-type:text/html;charset=GBKContent-length:100空行……..
class Client implements Runnable{
	private static String basePath="d:/web";
	private Socket socket;
	
	public Client(Socket socket){
		this.socket=socket;
	}
	
	@Override
	public void run() {
		PrintWriter writer=null;
		BufferedReader reader=null;
		BufferedReader freader=null;
		try {
			InputStream in=socket.getInputStream();
			OutputStream out=socket.getOutputStream();
			writer = new PrintWriter(new OutputStreamWriter(out));
			
			reader = new BufferedReader(new InputStreamReader(in));
			
			String firstLine=reader.readLine();
			String url=firstLine.split(" ")[1];
			String path=basePath+url;
			freader = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
			
			writer.write("HTTP/1.1 200 OK\r\n");
			writer.write("Content-type:text/html;charset=GBK\r\n");
			writer.write("\r\n");
			
			String s="";
			while((s=freader.readLine())!=null){
				writer.print(s);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
		writer.close();
		try {
			reader.close();
			freader.close();
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
		
	}
	
}

 

package server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	
	public void start() throws Exception{
		ServerSocket ser=new ServerSocket(7776);
		while(true){
			Socket socket=ser.accept();
			
			new Thread(new Client(socket)).start();
		}
	}
	
	
	public static void main(String[] args) throws Exception{
		new Server().start();
		
		
	}

}


 


 

你可能感兴趣的:(模拟Tomcat)