我想在Websockets上使用MQTT。在Netty中使用Websockets非常简单:
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("codec-http", new HttpServerCodec());
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
pipeline.addLast("handler", new WebSocketServerHandler());
我找到了基于Netty的MQTT经纪人(moquette)。
NettyMQTTHandler handler = new NettyMQTTHandler();
ServerBootstrap b = new ServerBootstrap();
b.group(m_bossGroup, m_workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//pipeline.addFirst("metrics", new BytesMetricsHandler(m_metricsCollector));
pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0, Constants.DEFAULT_CONNECT_TIMEOUT));
pipeline.addAfter("idleStateHandler", "idleEventHandler", new MoquetteIdleTimoutHandler());
//pipeline.addLast("logger", new LoggingHandler("Netty", LogLevel.ERROR));
pipeline.addLast("decoder", new MQTTDecoder());
pipeline.addLast("encoder", new MQTTEncoder());
pipeline.addLast("metrics", new MessageMetricsHandler(m_metricsCollector));
pipeline.addLast("handler", handler);
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.option(ChannelOption.SO_REUSEADDR, true)
.childOption(ChannelOption.SO_KEEPALIVE, true);
所以在理论上我应该能够通过Websocket发送MQTT,但我不知道是否可以使用Netty?有没有任何线索或想法如何做到这一点?我应该使用MessageToMessageCodec和BinaryWebSocketFrame吗?
干杯!
答案 0 :(得分:7)
让我假设您的MQTTDecoder
消耗ByteBuf
并生成一些MQTT消息对象,而MQTTEncoder
则相反,通常就是这种情况。
然后,您的编解码器使用的ByteBuf
不是Web Socket消息。它们需要成为Web Socket帧的有效载荷。我会将以下处理程序插入管道:
MessageToMessageDecoder
,它将WebSocket文本(或二进制)框架转换为ByteBuf
,以便MQTTDecoder
可以使用它。转换应该非常简单 - 只需获取Web Socket框架的内容。MessageToMessageEncoder
转换为Web Socket文本(或二进制)框架的ByteBuf
,以便Netty的WebSocketFrameEncoder
可以使用它。转换也应该非常简单 - 只需将ByteBuf
编码的MQTTEncoder
包装在Web Socket框架对象中。生成的管道如下所示:
HttpResponseEncoder
HttpRequestDecoder
HttpObjectAggregator(65536)
WebSocketServerProtocolHandler("/your-websocket-endpoint-path")
WebSocketFrameToByteBufDecoder
扩展MessageToMessageDecoder
ByteBufToWebSocketFrameEncoder
扩展MessageToMessageEncoder
MQTTEncoder
MQTTDecoder
MessageMetricsHandler
handler
WebSocketServerProtocolHandler
将与您的网络套接字客户端进行必要的握手,并在WebSocketFrameEncoder
之前插入WebSocketFrameDecoder
和WebSocketFrameToByteBufDecoder
。成功握手后生成的管道将如下所示:
WebSocketFrameEncoder
WebSocketFrameDecoder
WebSocketFrameToByteBufDecoder
扩展MessageToMessageDecoder
ByteBufToWebSocketFrameEncoder
扩展MessageToMessageEncoder
MQTTEncoder
MQTTDecoder
MessageMetricsHandler
handler