美文网首页程序员
编写自己的Tomcat服务器

编写自己的Tomcat服务器

作者: huhu502 | 来源:发表于2016-07-16 13:03 被阅读342次

概念

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

  • 服务器端开启端口为9999的socket等待客户端来访问它。
   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();
    }
}
  • 创建这个类的时候就可以获取客户端发送过来的请求。 并通过io流接收它。
 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();
    }
  }
  • 解析请求的数据,找到资源所在的位置,在这里就是找到C:\test\ROOT这个文件夹下面的资源。
    这是头部的信息:GET /a.png HTTP/1.1
   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];
}
  • 给客户端响应请求,按照下面的格式响应请求,并且判断一下如果有这个资源就返回200,没有这个资源就返回404.
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();
    }
  }

相关文章

网友评论

    本文标题:编写自己的Tomcat服务器

    本文链接:https://www.haomeiwen.com/subject/ticujttx.html