Search code examples
javatcpnettytcpclient

Netty TCP Client async messages


I am building a tcp client to receive and sending messages. I followed the steps on Netty user guide and wrote a simple tcp client with a custom handler extending the ChannelInboundHandlerAdapter.

In the hander I store the ChannelHandlerContext:

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

Then I have a send method which uses the ChannelHandlerContext to send messages:

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

The other option I have found is to use the Channel object in your client class

 channel.writeAndFlush (msg);

I need to call the send method from a different thread. What is the best way to do it ?

Thanks in advance.


Solution

  • Both ChannelHandlerContext and Channel are thread safe, so you can write from any thread without worrying.

    If you use Channel.write(), message will have to travel through the complete pipeline. But if you use ChannelHandlerContext.write() it will only have to travel through the upstream handlers in the pipeline. Therefore writing to ChannelHandlerContext is more efficient.

    And also note that most of the time its better to use writeAndFlush() instead of write().

    Have a look at this presentation for more details.