[英]Netty server message not making it to client
我正在尝试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选项'-Dio.netty.leakDetection.level = advanced'或调用ResourceLeakDetector.setLevel()有关更多信息,请参见http://netty.io/wiki/reference-counted-objects.html 。 。
请任何帮助或建议。 在此先感谢`
之所以会收到关于释放的消息,是因为您在处理程序添加的方法中分配了ByteBuf并将其分配给byteBuf,然后在channelRead中将byteBuf分配给了传入消息,从而导致第一个消息被垃圾回收而从未被释放。 通过不在handlerAdded中分配它来解决此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.