我正在使用Netty 4 RC1。我在客户端初始化管道:
public class NodeClientInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
// Frame encoding and decoding
sc.pipeline()
.addLast("logger", new LoggingHandler(LogLevel.DEBUG))
// Business logic
.addLast("handler", new NodeClientHandler());
}
}
NodeClientHandler具有以下相关代码:
public class NodeClientHandler extends ChannelInboundByteHandlerAdapter {
private void sendInitialInformation(ChannelHandlerContext c) {
c.write(0x05);
}
@Override
public void channelActive(ChannelHandlerContext c) throws Exception {
sendInitialInformation(c);
}
}
我使用以下方法连接到服务器:
public void connect(final InetSocketAddress addr) {
Bootstrap bootstrap = new Bootstrap();
ChannelFuture cf = null;
try {
// set up the pipeline
bootstrap.group(new NioEventLoopGroup())
.channel(NioSocketChannel.class)
.handler(new NodeClientInitializer());
// connect
bootstrap.remoteAddress(addr);
cf = bootstrap.connect();
cf.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture op) throws Exception {
logger.info("Connect to {}", addr.toString());
}
});
cf.channel().closeFuture().syncUninterruptibly();
} finally {
bootstrap.shutdown();
}
}
因此,我基本上想要做的是在通道处于活动状态(即连接成功)之后,将一些初始信息从客户端发送到服务器。但是,当执行
c.write()
时,我收到以下警告,并且没有包发送:WARNING: Discarded 1 outbound message(s) that reached at the head of the pipeline. Please check your pipeline configuration.
我知道我的管道中没有出站处理程序,但是(现在)我认为我不需要一个处理程序,而且我认为Netty会小心地将ByteBuffer传输到服务器上。我在管道配置中在做什么错?
最佳答案
如果您写入通道,Netty默认只处理ByteBuf类型的消息。因此,您需要将其包装在ByteBuf中。另请参见Unpooled类及其静态助手,以创建ByteBuf实例。