手写web server: 2-Http服务器

175 阅读1分钟

【声明】文章为本人学习时记录的笔记。 原课程地址:www.liaoxuefeng.com/wiki/154595…

1、http server的流程

1、监听tcp的端口,等待客户端连接
2、接受tpc连接后,处理请求
    2.1 接收浏览器发送的HTTP请求
    2.2 解析HTTP请求
    2.3 处理请求
    2.4 发送HTTP响应
3、重复整个2的大步骤,直到tcp链接关闭。

2、简易的http server的部件

2.1、Connector

connector的能力:

1、创建服务,监听端口(使用java内置jdk.httpserver)

public HttpConnector() throws IOException {  
    // start http server:  
    String host = "0.0.0.0";  
    int port = 8080;  
    this.httpServer = HttpServer.create(new InetSocketAddress(host, port), 0, "/", this);  
    this.httpServer.start();  
    logger.info("http server started at {}:{}...", host, port);  
}

2、接收请求,并处理请求 这里的请求和响应都在HttpExchange中(HttpExchange封装了HTTP请求和响应)。

   
    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String method = exchange.getRequestMethod();
        URI uri = exchange.getRequestURI();
        String path = uri.getPath();
        String query = uri.getRawQuery();
        logger.info("{}: {}?{}", method, path, query);
        Headers respHeaders = exchange.getResponseHeaders();
        respHeaders.set("Content-Type", "text/html; charset=utf-8");
        respHeaders.set("Cache-Control", "no-cache");
        // 设置200响应:
        exchange.sendResponseHeaders(200, 0);
        String s = "<h1>Hello, world.</h1><p>" + LocalDateTime.now().withNano(0) + "</p>";
        try (OutputStream out = exchange.getResponseBody()) {
            out.write(s.getBytes(StandardCharsets.UTF_8));
        }
    }