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 (将#修改为@)