搭建服务基本配置参考第1篇。本篇仅介绍实现WebSocket服务器的关键代码
initChannel
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(64 * 1024));
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
pipeline.addLast(new TextWebSocketFrameHandler()); //自定义
- HttpServerCodec和HttpObjectAggregator:是netty自带的,用于处理http请求的。我们知道WebSocket是ws请求,而不是http。而ws在第一次请求的时候,需要建立ws连接,此时是http。只有建立了ws长连接以后,后续的请求,才转变为ws通信。
- WebSocketServerProtocolHandler:参数ws,指当收到请求地址为 xxxxx/ws 时,将把当前连接转变成一个ws长连接。
- TextWebSocketFrameHandler:自定义的用于处理ws长连接的Handler,如下