首先还是在Netty官网找到demo的链接,Netty官网websocket demo 然后就是开始copy 对应的类 拿来测试了。
然后就开始分析添加对应的handler了。WebSocketServerInitializer 里配置了
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
if (sslCtx != null) {
pipeline.addLast(sslCtx.newHandler(ch.alloc()));
}
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new WebSocketServerCompressionHandler());
pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true));
pipeline.addLast(new WebSocketIndexPageHandler(WEBSOCKET_PATH));
pipeline.addLast(new WebSocketFrameHandler());
}
- pipeline.addLast(sslCtx.newHandler(ch.alloc())); 这个和https相关 一般不需要
- pipeline.addLast(new HttpServerCodec()); 这个用做http协议的编解码 初期http转websocket的过程中可以用到
- pipeline.addLast(new HttpObjectAggregator(65536)); http消息可能过大的时候分块了可以用这个合并下
- pipeline.addLast(new WebSocketServerCompressionHandler()); 看表面意思就是压缩的意思了 一般可以去掉
- pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true)); 这个就是http能升级成websocket的关键
- pipeline.addLast(new WebSocketIndexPageHandler(WEBSOCKET_PATH)); 这个代码加上去之后 就可以直接在浏览器里访问对应的端口测试websocket了
- pipeline.addLast(new WebSocketFrameHandler()); 最后这里就是处理websocketframe的地方了
- -