TCP 分隔数据报与 Netty 连接
TCP delimited Datagram concatenation with Netty
在理解图层时遇到一些挑战。
我有多个客户端连接到服务器。
每个客户端发送由 '\r\n'
终止的短数据报,但服务器处理不应开始,除非最终的 DELIMITER 到达(连接每个连接的块)。
- 我是否延长
DelimiterBasedFrameDecoder
- 我是否应该添加子管道并连接字符串(这样更容易)?但是如何保留
ChannelHandlerAdapter
中的先前块?
澄清挑战:我试图避免必须维护状态(以前的块)。
有什么示例或建议吗?
以防万一,在 Datagram
下你的意思是来自客户端的消息没有终止定界符 - 而 DelimiterBasedFrameDecoder
就完全没问题了。您也不必扩展它。您只需要将它添加到管道并在它之后的下一个处理程序中 - 您将收到 ByteBuf
准备好(累积)帧(客户端在终止定界符之前发送的所有数据)。
pipeline.addLast(new DelimiterBasedFrameDecoder(65536, Delimiters.lineDelimiter()));
pipeline.addLast(new MyHandler());
class MyHandler extends SimpleChannelInboundHandler<ByteBuf> {
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
//msg is accumulated frames from your client, before terminating delimiter
}
}
在理解图层时遇到一些挑战。
我有多个客户端连接到服务器。
每个客户端发送由 '\r\n'
终止的短数据报,但服务器处理不应开始,除非最终的 DELIMITER 到达(连接每个连接的块)。
- 我是否延长
DelimiterBasedFrameDecoder
- 我是否应该添加子管道并连接字符串(这样更容易)?但是如何保留
ChannelHandlerAdapter
中的先前块?
澄清挑战:我试图避免必须维护状态(以前的块)。
有什么示例或建议吗?
以防万一,在 Datagram
下你的意思是来自客户端的消息没有终止定界符 - 而 DelimiterBasedFrameDecoder
就完全没问题了。您也不必扩展它。您只需要将它添加到管道并在它之后的下一个处理程序中 - 您将收到 ByteBuf
准备好(累积)帧(客户端在终止定界符之前发送的所有数据)。
pipeline.addLast(new DelimiterBasedFrameDecoder(65536, Delimiters.lineDelimiter()));
pipeline.addLast(new MyHandler());
class MyHandler extends SimpleChannelInboundHandler<ByteBuf> {
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
//msg is accumulated frames from your client, before terminating delimiter
}
}