Skip to content

第 12 章:WebSocket ​

所属部分:Part 3 — Network Protocols(网络协议)
核心主题:基于 Netty 实现 HTTP 到 WebSocket 的协议升级、实时双向通信、静态页面与 WebSocket 混合服务端架构,以及基于 SSL/TLS 的安全 wss:// 通信。


1. 为什么需要 WebSocket? ​

在《Netty in Action》第 3 部分(网络协议)的开篇,作者 Norman Maurer 首先指出了传统 Web 通信模型的根本局限:

1.1 传统 HTTP 模型的痛点 ​

HTTP 协议本质上是**半双工(Half-Duplex)且由客户端驱动(Request-Response)**的:

  • 必须由客户端发起请求,服务端无法在没有收到请求的情况下主动向客户端推送数据。
  • 为了在浏览器中实现“看似实时”的通信(如聊天室、股票行情、协同编辑),开发者长期依赖两种折中方案(HTTP Hack):
    1. 短轮询(Short Polling):客户端每隔固定时间(如 1 秒)向服务端发送一次 HTTP 请求询问“有新数据吗?”。这会导致大量无意义的空响应、频繁的 TCP 连接建立/销毁或 HTTP 头部开销,极度浪费带宽与服务端资源。
    2. 长轮询(Long Polling / Comet):客户端发起请求后,服务端故意挂起连接(Hold),直到有新消息或超时才返回响应,客户端收到后立刻再发起下一次请求。虽然减少了无效请求次数,但每次推送仍需重新经历一次完整的 HTTP 请求-响应周期,依然存在高延迟和沉重的头部开销。

1.2 WebSocket 的核心优势与升级机制 ​

WebSocket(RFC 6455) 从协议层彻底解决了上述问题:

  • 全双工双向通信(Full-Duplex):在单个持久化的 TCP 连接上,客户端和服务端可以随时、独立地向对方发送数据,无需轮询。
  • 极低的协议开销:握手完成后,数据以轻量级的**帧(Frame)**形式传输,帧头通常只有 2 到 14 字节,远小于 HTTP 请求头。
  • 天然穿透防火墙与代理:WebSocket 复用了 HTTP/HTTPS 的标准端口(80 / 443),通过 HTTP/1.1 Upgrade 机制完成协议切换。

协议升级(Handshake)流程 ​

  1. 客户端发送一个普通的 HTTP/1.1 GET 请求,携带关键升级头信息:
    http
    GET /ws HTTP/1.1
    Host: localhost:9999
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
    Sec-WebSocket-Version: 13
  2. 服务端校验通过后,返回状态码 101 Switching Protocols:
    http
    HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
  3. 一旦 101 响应发送完成,底层的同一条 TCP 连接就正式脱离 HTTP 协议,后续所有双向流量均采用 WebSocket 帧协议进行传输。

2. 实时聊天室示例:整体架构设计 ​

为了直观演示 Netty 对 WebSocket 的原生支持,本章构建了一个基于浏览器的实时聊天室服务端(Chat Server)。

这个服务端需要同时承担两类职责,体现了一个非常典型的混合协议处理场景:

  1. 提供静态网页(HTTP):当用户用浏览器访问 http://localhost:9999/ 时,服务端返回 index.html(内含页面 UI 与 JavaScript WebSocket 客户端逻辑)。
  2. 处理实时消息(WebSocket):浏览器加载页面后,通过 JS 向 ws://localhost:9999/ws 发起连接升级;升级成功后,服务端将该连接加入聊天室群组,并将任意客户端发来的文本消息广播给所有在线客户端。

请求路由与 Pipeline 协作流转 ​

请求路由与 Pipeline 协作流转

Netty 提供了开箱即用的 WebSocket 帧模型(WebSocketFrame 及其 6 个子类),使业务代码无需手动解析二进制帧头:

帧类型说明
BinaryWebSocketFrame包含二进制数据(如图片、Protobuf 字节流)
TextWebSocketFrame包含 UTF-8 编码的文本数据(本章聊天室使用)
ContinuationWebSocketFrame属于前一个 BinaryWebSocketFrame 或 TextWebSocketFrame 的分片延续数据
PingWebSocketFrame心跳探测控制帧,用于检测对端是否存活
PongWebSocketFrame对 PingWebSocketFrame 的响应控制帧
CloseWebSocketFrame表示关闭连接请求的控制帧,包含状态码与关闭原因

3. 实现 WebSocket 服务端的核心组件 ​

按照作者的设计思路,服务端由 4 个核心组件自底向上组装而成:

  1. HttpRequestHandler(处理 HTTP 页面请求)
  2. TextWebSocketFrameHandler(处理 WebSocket 文本帧与连接事件)
  3. ChatServerInitializer(编排 ChannelPipeline)
  4. ChatServer(引导启动与优雅关闭)

3.1 处理 HTTP 请求:HttpRequestHandler ​

HttpRequestHandler 负责区分“普通 HTTP 请求”和“WebSocket 握手升级请求”。

  • 如果请求 URI 匹配 WebSocket 端点(例如 /ws),它不做处理,而是直接将请求透传给 ChannelPipeline 中的下一个 Handler(即 WebSocketServerProtocolHandler)。
  • 否则,它从本地磁盘读取 index.html 并作为 HTTP 响应返回给浏览器。
java
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedNioFile;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.URISyntaxException;
import java.net.URL;

public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    private final String wsUri;
    private static final File INDEX;

    static {
        URL location = HttpRequestHandler.class
                .getProtectionDomain()
                .getCodeSource()
                .getLocation();
        try {
            String path = location.toURI() + "index.html";
            path = !path.contains("file:") ? path : path.substring(5);
            INDEX = new File(path);
        } catch (URISyntaxException e) {
            throw new IllegalStateException("Unable to locate index.html", e);
        }
    }

    public HttpRequestHandler(String wsUri) {
        this.wsUri = wsUri;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        // 1. 如果是 WebSocket 升级请求,增加引用计数并传递给下一个 ChannelInboundHandler
        if (wsUri.equalsIgnoreCase(request.uri())) {
            ctx.fireChannelRead(request.retain());
        } else {
            // 2. 处理 HTTP 100 Continue 请求以符合 HTTP 1.1 规范
            if (HttpUtil.is100ContinueExpected(request)) {
                send100Continue(ctx);
            }

            // 3. 读取 index.html
            RandomAccessFile file = new RandomAccessFile(INDEX, "r");
            HttpResponse response = new DefaultHttpResponse(
                    request.protocolVersion(), HttpResponseStatus.OK);
            response.headers().set(
                    HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");

            boolean keepAlive = HttpUtil.isKeepAlive(request);
            if (keepAlive) {
                response.headers().set(HttpHeaderNames.CONTENT_LENGTH, file.length());
                response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            }

            // 4. 写回 HTTP 响应头
            ctx.write(response);

            // 5. 写回 index.html 内容(根据是否启用 SSL 选择零拷贝或分块传输)
            if (ctx.pipeline().get(SslHandler.class) == null) {
                ctx.write(new DefaultFileRegion(file.getChannel(), 0, file.length()));
            } else {
                ctx.write(new ChunkedNioFile(file.getChannel()));
            }

            // 6. 写入 LastHttpContent 标记响应体结束并刷新缓冲区
            ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
            if (!keepAlive) {
                future.addListener(ChannelFutureListener.CLOSE);
            }
        }
    }

    private static void send100Continue(ChannelHandlerContext ctx) {
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE);
        ctx.writeAndFlush(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

关键细节解析 ​

  1. 为什么必须调用 request.retain()?
    HttpRequestHandler 继承了 SimpleChannelInboundHandler<FullHttpRequest>。该基类会在 channelRead0() 方法返回后自动调用 ReferenceCountUtil.release(request) 释放引用计数。如果这里不先调用 request.retain() 将引用计数加 1,当 WebSocketServerProtocolHandler 异步或后续读取该 FullHttpRequest 时,就会因引用计数已归零而抛出 IllegalReferenceCountException。
  2. 零拷贝(DefaultFileRegion)与 SSL(ChunkedNioFile)的权衡:
    • 当没有使用 SSL/TLS 时,直接写入 DefaultFileRegion,Netty 会利用操作系统的 sendfile 系统调用将文件内容直接从文件系统缓存发送到网卡,无需经过用户态内存拷贝。
    • 当 Pipeline 中存在 SslHandler 时,数据必须在用户态经过 TLS 加密才能发送,无法使用内核态零拷贝,因此必须改用 ChunkedNioFile(配合 Pipeline 中的 ChunkedWriteHandler)逐块读取、加密并写出。

3.2 处理 WebSocket 帧:TextWebSocketFrameHandler ​

一旦升级握手成功,客户端与服务端之间传输的就是 WebSocket 帧。对于纯文本聊天室,我们只需关注 TextWebSocketFrame(Ping、Pong、Close 等控制帧由 WebSocketServerProtocolHandler 自动代劳)。

java
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private final ChannelGroup group;

    public TextWebSocketFrameHandler(ChannelGroup group) {
        this.group = group;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 监听 WebSocket 握手完成事件
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            // 1. 协议已升级为 WebSocket,不再需要接收 HTTP 请求,移除 HttpRequestHandler
            ctx.pipeline().remove(HttpRequestHandler.class);

            // 2. 向当前已连接的所有客户端广播新用户加入通知
            group.writeAndFlush(new TextWebSocketFrame(
                    "Client " + ctx.channel() + " joined"));

            // 3. 将当前新连接的 Channel 加入 ChannelGroup
            group.add(ctx.channel());
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        // 增加引用计数,并将收到的文本帧广播给 ChannelGroup 中的所有连接
        group.writeAndFlush(msg.retain());
    }
}

关键细节解析 ​

  1. 握手完成事件(HandshakeComplete):
    WebSocketServerProtocolHandler 在完成 HTTP 101 握手后,会向 Pipeline 触发一个用户事件(在 Netty 4.1+ 中为 WebSocketServerProtocolHandler.HandshakeComplete;原书基于早期 4.0 版本写法为 ServerHandshakeStateEvent.HANDSHAKE_COMPLETE,在现代 Netty 4.x 中建议使用 instanceof WebSocketServerProtocolHandler.HandshakeComplete)。
  2. 动态移除 HttpRequestHandler:
    连接升级完成后,该 TCP 连接上不会再有 HTTP 请求,移除 HttpRequestHandler 可以缩短 ChannelPipeline 的调用链,提升后续帧处理性能。
  3. 广播顺序与 ChannelGroup 自动清理:
    • 先调用 group.writeAndFlush(...) 再调用 group.add(ctx.channel()),这样新加入的客户端不会收到自己刚加入的提示。
    • ChannelGroup 内部会自动监听 Channel 的关闭事件:当某个客户端断开连接时,它会被自动从 ChannelGroup 中移除,无需手动编写 channelInactive 清理逻辑。
  4. 为什么 channelRead0 中也要 msg.retain()?
    同样是因为 SimpleChannelInboundHandler 会在 channelRead0 返回后释放 msg,而 group.writeAndFlush(...) 是异步操作——方法返回时,消息可能尚未真正编码并写入各个目标 Channel。因此必须调用 msg.retain() 保护数据不被提前释放。

3.3 初始化 ChannelPipeline:ChatServerInitializer ​

ChatServerInitializer 负责将上述所有 ChannelHandler 按严格顺序装配到每个新接入的 Channel 的 ChannelPipeline 中:

java
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class ChatServerInitializer extends ChannelInitializer<Channel> {
    private final ChannelGroup group;

    public ChatServerInitializer(ChannelGroup group) {
        this.group = group;
    }

    @Override
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(64 * 1024));
        pipeline.addLast(new HttpRequestHandler("/ws"));
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        pipeline.addLast(new TextWebSocketFrameHandler(group));
    }
}

每个 Handler 的顺序与职责 ​

顺序Handler方向核心职责
1HttpServerCodec入站 / 出站将入站字节解码为 HttpRequest / HttpContent,将出站 HttpResponse / HttpContent 编码为字节。
2ChunkedWriteHandler出站支持异步写入大数据流(如 ChunkedNioFile),防止大文件传输时发生内存溢出(OOM)。
3HttpObjectAggregator(64 * 1024)入站将一个 HttpMessage 和其后续多个 HttpContent 聚合成单个完整的 FullHttpRequest 或 FullHttpResponse,简化后续 Handler 的编程模型。
4HttpRequestHandler("/ws")入站处理普通 HTTP 请求(提供 index.html);遇到 /ws 升级请求时调用 retain() 并透传。
5WebSocketServerProtocolHandler("/ws")入站处理 /ws 的 WebSocket 握手升级、自动应答 Ping/Pong/Close 控制帧,并向 Pipeline 发出握手完成事件。
6TextWebSocketFrameHandler(group)入站响应握手完成事件(管理 ChannelGroup)并广播 TextWebSocketFrame。

握手升级前后 Pipeline 的动态重塑 ​

Netty 的 WebSocketServerProtocolHandler 非常智能。当它完成 101 Switching Protocols 握手后,会自动在运行时对 ChannelPipeline 进行“换血”:

  • 将原先的 HTTP 编解码器(HttpServerCodec)和聚合器(HttpObjectAggregator)替换为 WebSocket 帧解码器(WebSocket13FrameDecoder 等)和帧编码器(WebSocket13FrameEncoder 等)。
  • 再配合 TextWebSocketFrameHandler 手动移除 HttpRequestHandler,升级后的 Pipeline 就变成了一个纯粹、高效的 WebSocket 处理流水线:
text
[握手前]
HttpServerCodec -> ChunkedWriteHandler -> HttpObjectAggregator -> HttpRequestHandler -> WebSocketServerProtocolHandler -> TextWebSocketFrameHandler

[握手后]
WebSocketFrameDecoder -> WebSocketFrameEncoder -> ChunkedWriteHandler -> WebSocketServerProtocolHandler -> TextWebSocketFrameHandler

3.4 引导服务器:ChatServer ​

最后,通过 ChatServer 创建 EventLoopGroup、ChannelGroup,使用 ServerBootstrap 绑定端口,并注册 JVM 关闭钩子实现优雅停机:

java
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.ImmediateEventExecutor;

import java.net.InetSocketAddress;

public class ChatServer {
    private final ChannelGroup channelGroup =
            new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
    private final EventLoopGroup group = new NioEventLoopGroup();
    private Channel channel;

    public ChannelFuture start(InetSocketAddress address) {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(group)
                .channel(NioServerSocketChannel.class)
                .childHandler(createInitializer(channelGroup));
        ChannelFuture future = bootstrap.bind(address);
        future.syncUninterruptibly();
        channel = future.channel();
        return future;
    }

    protected ChannelInitializer<Channel> createInitializer(ChannelGroup group) {
        return new ChatServerInitializer(group);
    }

    public void destroy() {
        if (channel != null) {
            channel.close();
        }
        channelGroup.close();
        group.shutdownGracefully();
    }

    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            System.err.println("Please give port as argument");
            System.exit(1);
        }
        int port = Integer.parseInt(args[0]);
        final ChatServer endpoint = new ChatServer();
        ChannelFuture future = endpoint.start(new InetSocketAddress(port));

        // 注册关闭钩子,确保进程退出时优雅释放 Channel 与 EventLoopGroup
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                endpoint.destroy();
            }
        });
        future.channel().closeFuture().syncUninterruptibly();
    }
}

设计亮点:将 createInitializer(ChannelGroup group) 提取为 protected 工厂方法,正是为了方便下一节通过继承扩展出支持加密的 SecureChatServer,完美体现了面向对象开闭原则。


4. 加密 WebSocket(wss://) ​

在真实生产环境中,明文的 http:// 与 ws:// 面临窃听与中间人篡改风险;同时现代浏览器在 HTTPS 页面中也会强制拦截非加密的 ws:// 连接(Mixed Content 策略)。

借助 Netty ChannelPipeline 的可插拔架构,将聊天室升级为支持 TLS 加密的 https:// + wss:// 服务端无需修改任何一行业务逻辑代码,只需添加两个轻量级扩展类:

4.1 SecureChatServerInitializer ​

继承 ChatServerInitializer,在初始化 Pipeline 时将 SslHandler 插入到最前端(addFirst):

java
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;

import javax.net.ssl.SSLEngine;

public class SecureChatServerInitializer extends ChatServerInitializer {
    private final SslContext context;

    public SecureChatServerInitializer(ChannelGroup group, SslContext context) {
        super(group);
        this.context = context;
    }

    @Override
    protected void initChannel(Channel ch) throws Exception {
        super.initChannel(ch);
        SSLEngine engine = context.newEngine(ch.alloc());
        engine.setUseClientMode(false);
        // 必须放在 Pipeline 最前端:入站先解密,出站最后加密
        ch.pipeline().addFirst(new SslHandler(engine));
    }
}

前后呼应:还记得 HttpRequestHandler 中判断 if (ctx.pipeline().get(SslHandler.class) == null) 吗?当使用 SecureChatServerInitializer 时,该判断返回 false,自动切换为 ChunkedNioFile 分块发送 index.html,从而与 SslHandler 完美兼容。

4.2 SecureChatServer ​

继承 ChatServer,在 main 方法中借助 Netty 提供的 SelfSignedCertificate 快速生成开发测试用的自签名证书并构建 SslContext:

java
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

import java.net.InetSocketAddress;

public class SecureChatServer extends ChatServer {
    private final SslContext context;

    public SecureChatServer(SslContext context) {
        this.context = context;
    }

    @Override
    protected ChannelInitializer<Channel> createInitializer(ChannelGroup group) {
        return new SecureChatServerInitializer(group, context);
    }

    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            System.err.println("Please give port as argument");
            System.exit(1);
        }
        int port = Integer.parseInt(args[0]);

        // 仅用于开发与测试环境的自签名证书;生产环境请替换为 CA 签发的正式证书
        SelfSignedCertificate cert = new SelfSignedCertificate();
        SslContext context = SslContextBuilder
                .forServer(cert.certificate(), cert.privateKey())
                .build();

        final SecureChatServer endpoint = new SecureChatServer(context);
        ChannelFuture future = endpoint.start(new InetSocketAddress(port));
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                endpoint.destroy();
            }
        });
        future.channel().closeFuture().syncUninterruptibly();
    }
}

5. 测试与运行交互流程 ​

5.1 启动与浏览器验证 ​

  1. 编译并运行 ChatServer(例如传入端口参数 9999),或运行 SecureChatServer。
  2. 打开两个不同的浏览器窗口(Client A 与 Client B),访问:
    • 非加密模式:http://localhost:9999
    • 加密模式:https://localhost:9999(浏览器提示自签名证书风险时选择继续访问)
  3. 前端 index.html 加载后,通过 JavaScript 建立 WebSocket 连接:
    javascript
    var protocol = (window.location.protocol === "https:") ? "wss://" : "ws://";
    var ws = new WebSocket(protocol + window.location.host + "/ws");
    ws.onmessage = function(event) {
        // 将服务端广播的文本消息渲染到聊天窗口
    };

5.2 多客户端广播时序图 ​

多客户端广播时序图


6. 本章关键注意点与最佳实践总结 ​

  1. 引用计数管理(retain())不可遗漏:
    继承 SimpleChannelInboundHandler 时,框架会在 channelRead0 退出后自动释放消息对象。无论是将 FullHttpRequest 透传给下一个 Handler,还是将 TextWebSocketFrame 异步写入 ChannelGroup,都必须先调用 retain()。
  2. Handler 顺序决定协议处理成败:
    • HttpServerCodec -> ChunkedWriteHandler -> HttpObjectAggregator -> HttpRequestHandler -> WebSocketServerProtocolHandler -> TextWebSocketFrameHandler。
    • 启用加密时,SslHandler 必须通过 addFirst 放置在最前端。
  3. 零拷贝与 SSL 的互斥处理:
    DefaultFileRegion 依赖内核 sendfile,无法在用户态进行 TLS 加密。涉及静态文件传输且需要兼容 HTTPS 时,务必检查 Pipeline 中是否存在 SslHandler,并回退到 ChunkedNioFile。
  4. 善用 ChannelGroup 管理广播连接:
    DefaultChannelGroup 是线程安全的连接集合,不仅支持一键向所有在线客户端广播消息(writeAndFlush),还会在连接断开时自动清理失效 Channel,极大降低内存泄漏风险。