程序员

编写自己的Tomcat服务器

2016-07-16  本文已影响342人  huhu502

概念

其实本质是用到了socket。
1,首先客户端即浏览器访问自己设定的端口为9999的socket。
http://localhost:9999/a.png
2,服务器端就要将浏览器请求的数据进行解析,找到请求头中资源在tomcat中的位置的url,然后tomcat在自己本地寻找是否有这样的位置,如果找到了就按照浏览器响应的格式加上协议头部发送请求。

   public TomdogMain() {
    try {
        ServerSocket ss=new ServerSocket(9999);
        System.out.println("tomdog 已经在9999端口启动");
        while (true) {
            Socket client=ss.accept();
            System.out.println("有客户端链接起来了");
            new TomdogThread(client).start();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 public TomdogThread(Socket socket) {
    this.socket=socket;
    try {
        br=new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
        out=new PrintStream(this.socket.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
  }
   private String parse(BufferedReader br) {
    String[] data = null;
    try {
        String header=br.readLine();
        data=header.split(" ");
        System.out.println("Method:"+data[0]+"url:"+data[1]+"version:"+data[2]);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return data[1];
}
Paste_Image.png
   private void sendResponse(String url) {
    File file=new File(PATH,url);
    if(file.exists()){
        FileInputStream fileInputStream;
        try {
            fileInputStream = new FileInputStream(file);
            byte [] b=new byte[(int) file.length()];
            fileInputStream.read(b);
            out.println("HTTP/1.1 200 OK");
            out.println();//分割响应的头部和体部
            out.write(b);
            out.flush();
            out.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }else{
        out.println("HTTP/1.1 404 Not Found");
        out.println();
        out.print("<html><body><center><h1>File Not Found</h1></center></body></html>");
        out.flush();
        out.close();
    }
  }
上一篇 下一篇

猜你喜欢

热点阅读