【发布时间】:2015-09-28 09:59:27
【问题描述】:
为什么 channelRead() 不给我发送到服务器的完整消息?当消息超过 140 字节(大致,有时更多有时更少)时,有时会发生碎片。我正在使用使用 NioServerSocketChannel 类的 TCP 套接字。
我使用的是 4.1.0.Beta5。
有没有办法在邮件到达时阅读完整的邮件?
this.serverBootstrap = new ServerBootstrap();
this.serverBootstrap.group(new NioEventLoopGroup(1), new NioEventLoopGroup(6))
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>()
{
@Override
public void initChannel(SocketChannel ch) throws Exception
{
ch.pipeline().addLast(new TestServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, (int)Short.MAX_VALUE)
.option(ChannelOption.SO_RCVBUF, (int) Short.MAX_VALUE)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.TCP_NODELAY, true);
this.serverBootstrap.bind(this.host, this.port);
TestServerHandler 类扩展了 ChannelInboundHandlerAdapter:
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
String s = buffer.toString(CharsetUtil.UTF_8);
for(int i = 0; i < 20; i++)
{
s = s.replace("[" + ((char)i) + "]", i + "");
}
System.out.println(s.length() + "");
System.out.println();
System.out.println();
System.out.println(s);
}
我需要一种方法在它完全到达服务器时获取完整的 bytebuf / bytearray 并得到通知,以便我的应用程序可以根据客户端发送的数据以正确的方式响应。
简而言之:如何防止碎片化并让 channelRead 事件输出整个消息/字节缓冲区。
【问题讨论】:
-
快速浏览一下代码我会说你没有对
channelRead()中的味精Object做任何事情。