Netty 添加 websocket 支持

7 篇文章 0 订阅
  1. 首先还是在Netty官网找到demo的链接,Netty官网websocket demo 然后就是开始copy 对应的类 拿来测试了。

  2. 然后就开始分析添加对应的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的地方了
  • -
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值