码迷,mamicode.com
首页 > Web开发 > 详细

MQTT---HiveMQ源码详解(八)Netty-WebSocket

时间:2017-03-24 12:25:16      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:title   lock   ext   final   content   group   font   使用   string   

基于netty实现Webscoket相对来说就是相当简单,所以本讲中就不搞太复杂的了,给大家看一个类图,和一段给pipeline添加handler,就可以完全了解hivemq如何处理的了,其实跟几乎所有需要使用netty去支持websocket的处理一致。


技术分享


public class WebsocketTransportChannelInitializer {
    public static final int MAX_CONTENT_LENGTH = 65536;
    private final WebsocketListener listener;

    public WebsocketTransportChannelInitializer(WebsocketListener listener) {
        this.listener = listener;
    }

    public void initChannel(Channel channel) {
//添加http协议编码/解码
    channel.pipeline().addBefore(Pipelines.ALL_CHANNEL_GROUP_HANDLER, Pipelines.HTTP_SERVER_CODEC, new HttpServerCodec());
//添加HttpRequest消息聚合器
        channel.pipeline().addAfter(Pipelines.HTTP_SERVER_CODEC, Pipelines.HTTP_OBJECT_AGGREGATOR, new HttpObjectAggregator(MAX_CONTENT_LENGTH));
    //添加WebSocketServerProtocolHandler
        String path = this.listener.getPath();
        String subProtocols = getSubProtocols();
        boolean allowExtensions = this.listener.getAllowExtensions();
channel.pipeline().addAfter(Pipelines.HTTP_OBJECT_AGGREGATOR, Pipelines.WEBSOCKET_SERVER_PROTOCOL_HANDLER, new WebSocketServerProtocolHandler(path, subProtocols, allowExtensions, Integer.MAX_VALUE));
//添加Websocket字节码Handler
channel.pipeline().addAfter(Pipelines.WEBSOCKET_SERVER_PROTOCOL_HANDLER, Pipelines.WEBSOCKET_BINARY_FRAME_HANDLER, new WebsocketBinaryFrameHandler());
//添加websocket帧类型handler
channel.pipeline().addAfter(Pipelines.WEBSOCKET_BINARY_FRAME_HANDLER, Pipelines.WEBSOCKET_CONTINUATION_FRAME_HANDLER, new WebsocketContinuationFrameHandler());
//添加websocket文本handler
channel.pipeline().addAfter(Pipelines.WEBSOCKET_BINARY_FRAME_HANDLER, Pipelines.WEBSOCKET_TEXT_FRAME_HANDLER, new WebsocketTextFrameHandler());
//添加mqtt message转换成websocket
channel.pipeline().addAfter(Pipelines.WEBSOCKET_TEXT_FRAME_HANDLER, Pipelines.MQTT_WEBSOCKET_ENCODER, new MqttWebsocketEncoder());
    }

    @VisibleForTesting
    String getSubProtocols() {
        return Joiner.on(",").join(this.listener.getSubprotocols());
    }
}

MQTT交流群:221405150


MQTT---HiveMQ源码详解(八)Netty-WebSocket

标签:title   lock   ext   final   content   group   font   使用   string   

原文地址:http://blog.csdn.net/pipinet123/article/details/61194341

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!