美文网首页
基于Tomcat思想的简单web服务器(1)

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

作者: 初省 | 来源:发表于2019-05-07 20: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服务器应有的功能

相关文章

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

    本文是为了学习Tomcat源码之前,先理解web服务器的思想而写的 Tomcat作为web服务器,其实就是和客户端...

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

    在Spring中,只需要加上注解就可以自动寻找到匹配的方法,不需要web.xml配置路径,这虽然不算是web服务器...

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

    现在我们把原来的BIO改成基于netty的NIO 因为netty中自带了HTTPRequest,所以我们就不在需要...

  • Tomcat&

    Tomcat的学习 1.tomcat的解释 tomcat作用是发布网页中的. tomcat是web服务器 web容...

  • Web框架与Web服务器

    1. Web框架与服务器区别 ​ web服务器:典型Web服务器Apache、Nginx、Tomcat,作用是接...

  • tomcat安全加固和规范

    tomcat是一个开源Web服务器,基于Tomcat的Web运行效率高,可以在一般的硬件平台上流畅运行,因此,颇受...

  • 1.tomcat服务器的使用

    1.web开发入门的了解 2.常用的web服务器的厂商 3.Tomcat服务器的认识 4.Tomcat服务器目录结...

  • Nginx实战

    主流服务器比较 Tomcat:开源、运行servlet和jsp web应用软件基于java的web应用软件容器。对...

  • Servlet和JSP

    1、Servlet的工作原理 Servlet由tomcat服务器负责管理,Tomcat服务器通过读取web.xml...

  • Apache/Tomcat/JBOSS/Jetty/Nginx/

    总结:Apache/Tomcat/JBOSS/Nginx区别 . 1、Apache是Web服务器,Tomcat是应...

网友评论

      本文标题:基于Tomcat思想的简单web服务器(1)

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