ITPub博客

首页 > 应用开发 > Java > java实现一个支持 HTTP 1.1 长连接的 Web 服务器。

java实现一个支持 HTTP 1.1 长连接的 Web 服务器。

原创 Java 作者:tiannuo 时间:2026-05-13 14:02:53 0 删除 编辑

当然可以!下面我会给你一个完整的 Java 示例,实现一个支持 HTTP/1.1 长连接(Keep-Alive) 的简单 Web 服务器。这个服务器能处理多个请求,并在同一连接上保持通信,直到客户端关闭或超时。


核心思路

使用 ServerSocket 接收客户端连接。

使用 Socket 的输入输出流读取 HTTP 请求并发送响应。

检查 HTTP 头中的 Connection 字段:

如果是 Connection: keep-alive,则保持连接。

如果是 Connection: close 或 HTTP/1.0,关闭连接。

处理超时,避免服务器无限等待。

支持简单静态响应(你可以扩展成读取文件)。

示例代码

import java.io.*;

import java.net.*;

import java.util.*;


public class KeepAliveHttpServer {

    private static final int PORT = 8080;

    private static final int TIMEOUT = 5000; // 5秒超时


    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(PORT);

        System.out.println("HTTP 1.1 Keep-Alive Server started on port " + PORT);


        while (true) {

            Socket clientSocket = serverSocket.accept();

            System.out.println("Accepted connection from " + clientSocket.getInetAddress());

            // 交给线程处理

            new Thread(() -> handleClient(clientSocket)).start();

        }

    }


    private static void handleClient(Socket socket) {

        try {

            socket.setSoTimeout(TIMEOUT); // 设置读取超时

            InputStream input = socket.getInputStream();

            OutputStream output = socket.getOutputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(input));

            PrintWriter writer = new PrintWriter(output, true);


            boolean keepAlive = true;


            while (keepAlive) {

                // 读取请求行

                String requestLine = reader.readLine();

                if (requestLine == null || requestLine.isEmpty()) break;


                System.out.println("Request: " + requestLine);


                // 读取请求头

                Map<String, String> headers = new HashMap<>();

                String line;

                while (!(line = reader.readLine()).isEmpty()) {

                    int idx = line.indexOf(":");

                    if (idx > 0) {

                        String key = line.substring(0, idx).trim();

                        String value = line.substring(idx + 1).trim();

                        headers.put(key.toLowerCase(), value);

                    }

                }


                // 检查 Connection 字段

                String connectionHeader = headers.get("connection");

                if (connectionHeader != null) {

                    keepAlive = connectionHeader.equalsIgnoreCase("keep-alive");

                } else {

                    // HTTP/1.1 默认长连接

                    keepAlive = true;

                }


                // 构建响应

                String body = "<html><body><h1>Hello, HTTP 1.1 Keep-Alive!</h1></body></html>";

                int contentLength = body.getBytes().length;


                writer.print("HTTP/1.1 200 OK\r\n");

                writer.print("Content-Type: text/html\r\n");

                writer.print("Content-Length: " + contentLength + "\r\n");

                if (keepAlive) {

                    writer.print("Connection: keep-alive\r\n");

                } else {

                    writer.print("Connection: close\r\n");

                }

                writer.print("\r\n"); // 空行表示头结束

                writer.print(body);

                writer.flush();

            }

        } catch (SocketTimeoutException e) {

            System.out.println("Connection timed out.");

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                socket.close();

                System.out.println("Connection closed.");

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

}

关键点解释

长连接处理

HTTP/1.1 默认启用长连接。

通过 Connection: close 可以强制关闭。

服务器循环读取请求,直到超时或客户端关闭。

超时机制

socket.setSoTimeout(TIMEOUT) 防止客户端挂起导致服务器阻塞。

并发处理

每个客户端连接由一个线程处理,避免阻塞主线程。

响应头

必须包含 Content-Length,浏览器才知道响应结束。

测试方法

运行 Java 服务器:

java KeepAliveHttpServer

用浏览器访问:

http://localhost:8080

用 curl 测试长连接:

curl -v --http1.1 http://localhost:8080

curl -v --http1.1 -H "Connection: keep-alive" http://localhost:8080


你会看到同一个 TCP 连接可以处理多个请求。


https://vk.com/club238613049 https://vk.com/topic-238613049_61620133 https://vk.com/topic-238613049_61620133 https://vk.com/topic-238613049_61660416 https://vk.com/topic-238613049_61661015 https://vk.com/topic-238613049_61662370 https://vk.com/topic-238613049_61663127 https://vk.com/topic-238613049_61663727 https://vk.com/topic-238613049_61664344 https://vk.com/topic-238613049_61665403 https://vk.com/topic-238613049_61666396 https://vk.com/topic-238613049_61666859 https://vk.com/topic-238613049_61667466 https://vk.com/topic-238613049_61667973 https://vk.com/topic-238613049_61668424 https://vk.com/topic-238613049_61668843 https://vk.com/topic-238613049_61669431 https://vk.com/topic-238613049_61669923 https://vk.com/topic-238613049_61670528 https://vk.com/topic-238613049_61671056 https://vk.com/topic-238613049_61672040 https://vk.com/topic-238613049_61673949 https://vk.com/topic-238613049_61674520 https://vk.com/topic-238613049_61675099 https://vk.com/topic-238613049_61675713 https://vk.com/topic-238613049_61676862 https://vk.com/topic-238613049_61677472 https://vk.com/topic-238613049_61678068 https://vk.com/topic-238613049_61678633 https://vk.com/topic-238613049_61679471 https://vk.com/topic-238613049_61680104 https://vk.com/topic-238613049_61680977 https://vk.com/topic-238613049_61682733 https://vk.com/topic-238613049_61683900 https://vk.com/topic-238613049_61685288 https://vk.com/topic-238613049_61687400 https://vk.com/topic-238613049_61688091 https://vk.com/topic-238613049_61688892 https://vk.com/topic-238613049_61689625 https://vk.com/topic-238613049_61692163 https://vk.com/topic-238613049_61694912 https://vk.com/topic-238613049_61696022 https://vk.com/topic-238613049_61697404 https://vk.com/topic-238613049_61699759 https://vk.com/topic-238613049_61700290 https://vk.com/topic-238613049_61703158 https://vk.com/topic-238613049_61710898 https://vk.com/topic-238613049_61712349 https://vk.com/topic-238613049_61715121 https://vk.com/topic-238613049_61716645 https://vk.com/topic-238613049_61718235 https://vk.com/topic-238613049_61719514 https://vk.com/topic-238613049_61719966 https://vk.com/topic-238613049_61720951 https://vk.com/topic-238613049_61723091 https://vk.com/topic-238613049_61723610 https://vk.com/topic-238613049_61724095 https://vk.com/topic-238613049_61725830 https://vk.com/topic-238613049_61727910 https://vk.com/topic-238613049_61728369 https://vk.com/topic-238613049_61734596 https://vk.com/topic-238613049_61735204 https://vk.com/topic-238613049_61735918 https://vk.com/topic-238613049_61738211 https://vk.com/topic-238613049_61742986 https://vk.com/topic-238613049_61743758 https://vk.com/topic-238613049_61744456 https://vk.com/topic-238613049_61745154 https://vk.com/topic-238613049_61746305 https://vk.com/topic-238613049_61747520 https://vk.com/topic-238613049_61749937 https://vk.com/topic-238613049_61753913 https://vk.com/topic-238613049_61754322 https://vk.com/topic-238613049_61755170 https://vk.com/topic-238613049_61758587 https://vk.com/topic-238613049_61759748 https://vk.com/topic-238613049_61760124 https://vk.com/topic-238613049_61760703 https://vk.com/topic-238613049_61761029 https://vk.com/topic-238613049_61762073 https://vk.com/topic-238613049_61764542 https://vk.com/topic-238613049_61765991 https://vk.com/topic-238613049_61766666 https://vk.com/topic-238613049_61767428 https://vk.com/topic-238613049_61768459 https://vk.com/topic-238613049_61770494 https://vk.com/topic-238613049_61772768 https://vk.com/topic-238613049_61773220 https://vk.com/topic-238613049_61773366 https://vk.com/topic-238613049_61773872 https://vk.com/topic-238613049_61774188 https://vk.com/topic-238613049_61774912 https://vk.com/topic-238613049_61775489 https://vk.com/topic-238613049_61777185 https://vk.com/topic-238613049_61777359 https://vk.com/topic-238613049_61778096 https://vk.com/topic-238613049_61779337 https://vk.com/topic-238613049_61779962 https://vk.com/topic-238613049_61780146 https://vk.com/topic-238613049_61780848 https://vk.com/topic-238613049_61781349 https://vk.com/topic-238613049_61781714 https://vk.com/topic-238613049_61784007 https://vk.com/topic-238613049_61784224 https://vk.com/topic-238613049_61785616 https://vk.com/topic-238613049_61787896 https://vk.com/topic-238613049_61791261 https://vk.com/topic-238613049_61792829 https://vk.com/topic-238613049_61796205 https://vk.com/topic-238613049_61796572 https://vk.com/topic-238613049_61797600 https://vk.com/topic-238613049_61798992 https://vk.com/topic-238613049_61799871 https://vk.com/topic-238613049_61800137 https://vk.com/topic-238613049_61800423 https://vk.com/topic-238613049_61802707 https://vk.com/topic-238613049_61803481 https://vk.com/topic-238613049_61805679 https://vk.com/topic-238613049_61811434

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70050070/viewspace-3117737/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2026-05-08

  • 博文量
    74
  • 访问量
    66702