Netty 4 - 丢弃管道头的出站消息

时间:2013-04-02 10:40:21

标签: java netty

我正在使用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传输到服务器。我在管道配置中做错了什么?

1 个答案:

答案 0 :(得分:1)

如果您写入频道,Netty默认只处理ByteBuf类型的消息。所以你需要将它包装在ByteBuf中。另请参阅Unpooled类及其静态帮助程序以创建ByteBuf实例。