1. 程式人生 > >MQTT---HiveMQ源代碼具體解釋(八)Netty-WebSocket

MQTT---HiveMQ源代碼具體解釋(八)Netty-WebSocket

lang pos oid prot views com lan get onf

源博客地址:http://blog.csdn.net/pipinet123


MQTT交流群:221405150


基於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---HiveMQ源代碼具體解釋(八)Netty-WebSocket