首页 > 解决方案 > Netty 发送 2 个数据包而不是 1 个

问题描述

我正在使用 netty 迈出第一步,我想知道 netty 的以下行为:

当我使用以下处理程序时:

public class SimpleServerHandler extends ChannelInboundHandlerAdapter {

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf inBuffer = (ByteBuf) msg;

    String received = inBuffer.toString(CharsetUtil.UTF_8);
    System.out.println(dateFormat.format(new Date()) + " Server received: " + received);

    ctx.writeAndFlush(Unpooled.copiedBuffer("Hello " + received, CharsetUtil.UTF_8));
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();
}
}

然后我用“Packet Sender”发送一个 TCP 数据包我得到三个数据包

第一个是从“数据包发送者”到服务器,第二个是来自服务器的响应(类似于“Hello testtest”)然后......我不知道这个数据包来自哪里: 第三个来自服务器到“数据包发送者”,没有任何内容

我的服务器 java 是:

public class MainNettyApplicationServer {

public static void main(String[] args) throws InterruptedException {
    EventLoopGroup group = new NioEventLoopGroup();

    try {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(group);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.localAddress(new InetSocketAddress("10.0.0.2", 11111));

        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new SimpleServerHandler());
            }
        });
        ChannelFuture channelFuture = serverBootstrap.bind().sync();
        System.out.println("Server started.");
        channelFuture.channel().closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully().sync();
    }
}

}

标签: javatcpnetty

解决方案


推荐阅读