Netty TCP 客户端异步消息

Netty TCP Client async messages

我正在构建一个 tcp 客户端来接收和发送消息。 我按照 Netty user guide 上的步骤编写了一个简单的 tcp 客户端,其中包含一个扩展 ChannelInboundHandlerAdapter 的自定义处理程序。

在处理程序中我存储 ChannelHandlerContext:

 @Override
 public void channelActive (ChannelHandlerContext ctx) throws Exception {
   super.channelActive (ctx);
   this.ctx = ctx;
 }

然后我有一个使用 ChannelHandlerContext 发送消息的发送方法:

 public void sendMessage (String msg) {
  if (ctx == null) {
    return;
  }
  ChannelFuture cf = ctx.write (Unpooled.copiedBuffer (msg, CharsetUtil.UTF_8));
  ctx.flush ();
}

我发现的另一个选择是在您的客户端 class

中使用 Channel 对象
 channel.writeAndFlush (msg);

我需要从不同的线程调用发送方法。 最好的方法是什么?

提前致谢。

ChannelHandlerContextChannel 都是线程安全的,因此您可以从任何线程写入而无需担心。

如果您使用 Channel.write(),消息将必须通过完整的管道。但是如果你使用 ChannelHandlerContext.write() 它将只需要通过管道中的上游处理程序。因此写入 ChannelHandlerContext 效率更高。

还要注意,大多数时候最好使用 writeAndFlush() 而不是 write()

查看 this presentation 了解更多详情。