基于Tomcat思想的简单web服务器(1)

2019-05-07  本文已影响0人  初省

本文是为了学习Tomcat源码之前,先理解web服务器的思想而写的

Tomcat作为web服务器,其实就是和客户端建立socket连接,然后解析http数据报,然后转发给servlet类

http请求类
负责解析http数据报,获得uri和method,封装成一个对象

public class HTTPRequest {

    private String uri;

    private String method;

    public HTTPRequest(InputStream inputStream) throws IOException {
        byte[] bytes = new byte[1024];
        String httpRequest = "";
        int length = -1;
        if ((length = inputStream.read(bytes)) > 0) {
            httpRequest = new String(bytes, 0, length);
        }

        //        http报文格式:
        //        GET /favicon.ico HTTP/1.1
        //        Exception in thread "Thread-5" java.lang.NullPointerException
        //        Host: localhost:8888
        //        Connection: keep-alive
        //        Pragma: no-cache
        //        Cache-Control: no-cache
        //        at com.example.fall.WebServer.WebServer.dispatcher(WebServer.java:76)
        //        User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36
        //        Accept: image/webp,image/apng,image/*,*/*;q=0.8
        //        Referer: http://localhost:8888/hello
        //        at com.example.fall.WebServer.WebServer.service(WebServer.java:63)
        //        Accept-Encoding: gzip, deflate, br
        //        Accept-Language: zh-CN,zh;q=0.9
        //        Cookie: 省略

        // 获得http请求头
        String httpHeader = httpRequest.split("\n")[0];
        // 获取请求头的里方法和uri
        method = httpHeader.split("\\s")[0];
        uri = httpHeader.split("\\s")[1];
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

}

http响应类
负责将数据返回给前端

public class HTTPResponse {

    private OutputStream outputStream;

    public HTTPResponse(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void write(String message) throws IOException {
        // 必须加在响应头中
        outputStream.write("HTTP/1.1 200 OK\n".getBytes());
        outputStream.write("Content-Type: text/html; charset=UTF-8\n\n".getBytes());
        outputStream.write(message.getBytes());
    }

}

抽象servlet类
封装了处理的过程

public abstract class Servlet {

    public abstract void doGet(HTTPRequest httpRequest, HTTPResponse httpResponse) throws IOException;

    public abstract void doPost(HTTPRequest httpRequest, HTTPResponse httpResponse) throws IOException;

    public void service(HTTPRequest httpRequest, HTTPResponse httpResponse) throws IOException {
        if ("GET".equals(httpRequest.getMethod())) {
            doGet(httpRequest, httpResponse);
        } else if ("POST".equals(httpRequest.getMethod())) {
            doPost(httpRequest, httpResponse);
        }
    }

}

一个简单的hello响应类

public class HelloServlet extends Servlet {

    @Override
    public void doGet(HTTPRequest httpRequest, HTTPResponse httpResponse) throws IOException {
        httpResponse.write("hello Get");
    }

    @Override
    public void doPost(HTTPRequest httpRequest, HTTPResponse httpResponse) throws IOException {
        httpResponse.write("hello Post");
    }

}

Mapping对象
保存了映射关系

public class ServletMapping {

    private String servletName;

    private String uri;

    private String clazz;

    public ServletMapping(String servletName, String uri, String clazz) {
        this.servletName = servletName;
        this.uri = uri;
        this.clazz = clazz;
    }

    public String getServletName() {
        return servletName;
    }

    public void setServletName(String servletName) {
        this.servletName = servletName;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getClazz() {
        return clazz;
    }

    public void setClazz(String clazz) {
        this.clazz = clazz;
    }

}

Mapping配置类
Servlet中的web.xml就是保存了映射关系,这边模拟了xml加载的过程

public class ServletMappingConfig {

    public static List<ServletMapping> list = new ArrayList<>();

    static {
        list.add(new ServletMapping("hello","/hello","com.example.fall.WebServer.HelloServlet"));
    }

}

Server主类

public class WebServer {

    private static Logger logger = LoggerFactory.getLogger(WebServer.class);

    private int port;

    private ServerSocket serverSocket;

    private HashMap<String, ServletMapping> hashMap;

    public WebServer(int port) throws IOException {
        this.port = port;
        init();
    }

    private void init() throws IOException {
        serverSocket = new ServerSocket(port);
        hashMap = new HashMap<>();
        for (ServletMapping i : ServletMappingConfig.list) {
            hashMap.put(i.getUri(), i);
        }
        logger.info("服务器启动");
    }

    private void start() throws IOException {
        while (true) {
            Socket socket = serverSocket.accept();
            logger.info("接收到客户端连接, " + socket.getInetAddress() + ":" + socket.getPort());
            new Thread(new Runnable() {
                @Override
                public void run() {
                    service(socket);
                }
            }).start();
        }
    }

    private void service(Socket socket) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = socket.getInputStream();
            out = socket.getOutputStream();
            HTTPRequest httpRequest = new HTTPRequest(in);
            HTTPResponse httpResponse = new HTTPResponse(out);
            dispatcher(httpRequest, httpResponse);
        } catch (IOException | ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void dispatcher(HTTPRequest httpRequest, HTTPResponse httpResponse) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        String clazz = hashMap.get(httpRequest.getUri()).getClazz();
        Class<Servlet> servletClass = (Class<Servlet>) Class.forName(clazz);
        Servlet servlet = servletClass.newInstance();
        servlet.service(httpRequest, httpResponse);
    }


    public static void main(String[] args) throws IOException {
        new WebServer(8888).start();
    }

}
访问http://localhost:8888/hello
页面上会显示hello Get

这样我们已经初步完成了一个简单的web服务器,在这里我们为每一个socket都分配了一个子线程完成任务,一旦连接很多就会发生严重阻塞,所以我们接下来需要逐步为这个简单的web服务器增加NIO,注解Mapping,参数解析等功能,使其具有一个简单web服务器应有的功能

上一篇 下一篇

猜你喜欢

热点阅读