我正在使用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();
}
}
}