我正在尝试netty,但看起来客户端在我回复时没有收到我的消息。我使用Java NIO和socketChannel编写了相同的代码,看起来很好。我这样说是因为客户端记录了我发送的日志。下面是我的服务器
public class Server{
public void init(final int port){
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_REUSEADDR, true)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new ServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = bootstrap.bind("localhost", port).sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
System.out.println("Server encountered an InterruptedException");
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
以下是我的服务器处理程序
public class ServerHandler extends ChannelInboundHandlerAdapter {
public static Logger LOG = LoggerFactory.getLogger(UTPServerHandler.class);
final int LEN = 1028;
private ByteBuf byteBuf;
private MyDecoder myDecoder;
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
byteBuf = ctx.alloc().buffer(MAX_PACKET_LENGTH);
myDecoder = new MyDecoder();
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
byteBuf.release();
byteBuf = null;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
byteBuf = (ByteBuf) msg;
myDecoder.decodeMessage(byteBuf, ctx); //This is where I try to decode which message and respond. I pass ctx along so I know which to reponsd to. See sample response below
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
System.out.println"Got an exception...");
ctx.close();
}
}
示例回复:
public static void dummyResponse(ChannelHandlerContext ctx, int test){
ByteBuf response = Unpooled.buffer(32);
response.writeByte(test);
response.writeByte(test);
response.writeByte(test);
response.writeByte(test);
response.writeByte(test);
ctx.channel().writeAndFlush(response);
}
我正在我的盒子上做一个tcpdump,我看到我在线上发送了什么,所以我不确定我做错了什么。此外,几分钟后,这会被记录下来,我不确定我在服务器或服务器处理程序中做了什么来抱怨:
`2016-10-25 16:58:38.974 [nioEventLoopGroup-3-1] |错误|泄漏:ByteBuf.release()在被垃圾收集之前没有被调用。启用高级泄漏报告以找出泄漏发生的位置。要启用高级泄漏报告,请指定JVM选项&#39; -Dio.netty.leakDetection.level = advanced&#39;或者调用ResourceLeakDetector.setLevel()有关详细信息,请参阅http://netty.io/wiki/reference-counted-objects.html。
请提供任何帮助或建议。提前致谢 `
答案 0 :(得分:0)
您收到有关发布的消息,因为您在handlerAdded方法中分配了ByteBuf并将其分配给byteBuf,然后在channelRead中将byteBuf分配给您的传入消息,导致第一个被垃圾收集而不会被释放。通过不在handlerAdded中分配它来解决这个问题。