What is the best way to connect after connecting to Netty

A simple scenario:

  • A lower level class A that extends SimpleChannelUpstreamHandler. This class is the workhorse for sending a message and receiving a response.
  • Class B is a top-level class that can be used by another part of the system to send and receive messages (it can simulate synchronous and asynchronous). This class creates ClientBootstrap, sets up the factory pipeline, calls bootstrap.connect (), and ultimately gets a class A handle / link through which it will be used to send and receive the message. Something like:

    ChannelFuture future = bootstrap.connect(); Channel channel = future.awaitUninterruptibly().getChannel(); 

    Handler = channel.getPipeline (). get (A.class);

I know in class A, I can override public void channelClosed (ChannelHandlerContext ctx, ChannelStateEvent e); so when the remote server is down, I can receive notifications.

Since after the channel is closed, the original class A (the handler above) in class B is no longer valid, so I need to replace it with a new link.

Ideally, I want class A notification mechanism to be installed in class A in the above method with a private channel, so bootstrap.connect can be called again in class B. One way to do this is to have a link in class A that is reference class B. To do this, I will need to pass the class B reference to PipelineFactory, and then pass the PipelineFactory reference B to A.

Any other easier way to achieve the same?

thanks,

+7
java netty
source share
1 answer

Channel.closeFuture() returns a ChannelFuture that will notify you when the channel is closed. You can add ChannelFutureListener to the future in B so you can make another connection attempt.

You probably want to repeat this until the connection attempt completes completely:

 private void doConnect() { Bootstrap b = ...; b.connect().addListener((ChannelFuture f) -> { if (!f.isSuccess()) { long nextRetryDelay = nextRetryDelay(...); f.channel().eventLoop().schedule(nextRetryDelay, ..., () -> { doConnect(); }); // or you can give up at some point by just doing nothing. } }); } 
+14
source share

All Articles