How Tomcat works之(一个简单的web服务器)

来源:互联网 发布:网络整合营销 编辑:程序博客网 时间:2024/05/21 23:24

一、描述

1、这里简单的描述一下web服务器的工作流程,从浏览器请求,到服务器的响应。

2、采用java中的serversocket类

3、需要的环境是 maven3.3.9,jdk1.8

二、实现

1、新建一个maven项目tomcat,目录如下

这里写图片描述

2、首先是用来接收请求的serversocket,他的作用是:接受浏览器的请求,并把请求数据封装给request,在调用response进行响应。代码如下

HttpServer.java

package ex01;import java.net.Socket;import java.net.ServerSocket;import java.net.InetAddress;import java.io.InputStream;import java.io.OutputStream;import java.io.IOException;import java.io.File;/** * * 负责接收请求 * 1、把请求的数据封装到request * 3、把request设置给response * 2、然后调用response进行相应 * */public class HttpServer {  /**   * 得到静态资源目录   */  public static final String WEB_ROOT =    System.getProperty("user.dir") + File.separator  + "webroot";  // shutdown command  private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";  // the shutdown command received  private boolean shutdown = false;  public static void main(String[] args) {    System.out.println(WEB_ROOT);    HttpServer server = new HttpServer();    server.await();  }  public void await() {    ServerSocket serverSocket = null;    int port = 8080;    try {      serverSocket =  new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));    }    catch (IOException e) {      e.printStackTrace();      System.exit(1);    }    // Loop waiting for a request    while (!shutdown) {      Socket socket = null;      InputStream input = null;      OutputStream output = null;      try {        socket = serverSocket.accept();        input = socket.getInputStream();        output = socket.getOutputStream();        // create Request object and parse        Request request = new Request(input);        request.parse();        // create Response object        Response response = new Response(output);        response.setRequest(request);        response.sendStaticResource();        // Close the socket        socket.close();        //check if the previous URI is a shutdown command        shutdown = SHUTDOWN_COMMAND.equals(request.getUri());      }      catch (Exception e) {        e.printStackTrace();        continue;      }    }  }}

3、创建request类,他负责解析请求数据,并对其进行封装。

Request.java

package ex01;import java.io.InputStream;import java.io.IOException;/** * 1、负责解析请求的url * */public class Request {  private InputStream input;  private String uri;  public Request(InputStream input) {    this.input = input;  }  /**   * 接受请求数据,转化为string   */  public void parse() {    // Read a set of characters from the socket    StringBuffer request = new StringBuffer(2048);    int i;    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.print(request.toString());    uri = parseUri(request.toString());  }  /**   * 查找第一个和第二个空格,并取出url   * @param requestString   * @return   */  private String parseUri(String requestString) {    int index1, index2;    index1 = requestString.indexOf(' ');    if (index1 != -1) {      index2 = requestString.indexOf(' ', index1 + 1);      if (index2 > index1)        return requestString.substring(index1 + 1, index2);    }    return null;  }  public String getUri() {    return uri;  }}

4、之后是response响应类,他负责读取静态资源的信息,并把它返回给浏览器

Response.java

package ex01;import java.io.OutputStream;import java.io.IOException;import java.io.FileInputStream;import java.io.File;/*  HTTP Response = Status-Line    *(( general-header | response-header | entity-header ) CRLF)    CRLF    [ message-body ]    Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF*//** * 响应 */public class Response {    private static final int BUFFER_SIZE = 1024;    Request request;    OutputStream output;    public Response(OutputStream output) {        this.output = output;    }    /**     * 设置request     * @param request     */    public void setRequest(Request request) {        this.request = request;    }    /**     * 1、找到对应的静态资源     * 2、读取数据     * 3、进行相应     * @throws IOException     */    public void sendStaticResource() throws IOException {        byte[] bytes = new byte[BUFFER_SIZE];        FileInputStream fis = null;        try {            File file = new File(HttpServer.WEB_ROOT, request.getUri());            if (file.exists()) {                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);                }            } else {                // file not found                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>";                output.write(errorMessage.getBytes());            }        } catch (Exception e) {            // thrown if cannot instantiate a File object            System.out.println(e.toString());        } finally {            if (fis != null)                fis.close();        }    }}

5、需要其运行还需要在根目录下创建一个webroot目录,这个目录根据你在httpServer中写的。然后在里面创建index.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body>hello</body></html>

6、然后启动ie 由于谷歌不接受服务器返回的数据,所以使用的ie,输入以下地址

http://127.0.0.1:8080/index.html

7、效果如下

这里写图片描述

8、源码下载地址

https://gitee.com/lgr123/tomcat/tree/master/
阅读全文
0 0
原创粉丝点击