如何解决Java Netty TCP 消息在 channelread 时间歇性地被截断为 1420 字节
有人知道如何解决 netty 服务器接收到的截断消息的问题吗?我尝试使用原生 netty 和 reactor netty 但我仍然遇到同样的问题。我也尝试使用不同的解码器/编码器,但没有解决我的问题。我也尝试更改帧长度配置。这种情况每 500-1000 个请求发生一次。如果服务器和客户端驻留在同一台机器上,则不会发生这种情况。我期待 1494 字节,但有时我只收到 1420 字节
public final class Server {
public static void main(String[] args) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ServerInitializer());
ChannelFuture f = b.bind(8888);
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
@Sharable
public class ServerHandler extends SimpleChannelInboundHandler<byte[]> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
}
@Override
public void channelRead0(ChannelHandlerContext ctx,byte[] request) throws Exception {
ChannelFuture future = ctx.write(request);
future.addListener(ChannelFutureListener.CLOSE);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) {
cause.printstacktrace();
ctx.close();
}
}
public class ServerInitializer extends ChannelInitializer<SocketChannel> {
private static final ServerHandler SERVER_HANDLER = new ServerHandler();
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new DelimiterBasedFrameDecoder(8192,Delimiters.lineDelimiter()));
pipeline.addLast(new ByteArrayDecoder());
pipeline.addLast(new ByteArrayEncoder());
pipeline.addLast(SERVER_HANDLER);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。