Reconnecting a client automatically *without losing state*

brunodecarvalho kindernade at gmail.com
Mon Aug 2 10:05:38 EDT 2010


I use a listener-based approach.

public interface YourHandlerListener {
  void connectionFailed(YourHandler handler);
  void connectionGracefullyTerminated(YourHandler handler);
  void connectionAbruptlyTerminated(YourHandler handler);
}

public interface YourHandler extends ChannelHandler {
  String getHost();
  int getPort();
  void disconnect();
  boolean write(TypeOfWhateverYouWrite data);
}

public class YourHandlerImpl extends SimpleChannelUpstreamHandler
    implements YourHandler {

  private final String host;
  private final int port;
  private final YourHandlerListener listener;

  private Channel channel;
  private boolean requestedTerminate;

  public YourHandlerImpl(String host, int port, YourHandlerListener
listener) {
    // set internal vars
  }

  @Override
  public void exceptionCaught(...) {
    if ((this.channel != null) && this.channel.isConnected()) {
      this.channel.close();
    }
  }

  @Override
  public void channelConnected(...) {
    this.channel = e.getChannel();
  }

  @Override
  public void channelClosed(...) {
    // should be synch'd because of terminate()
    if (this.channel == null) {
      this.listener.connectionFailed(this);
    } else if (!this.requestedTerminate) {
      this.listener.connectionAbruptlyTerminated(this);
    } else {
      this.listener.connectionGracefullyTerminated(this);
    }
    this.channel = null;
  }

  @Override
  public void terminate() {
    // it's a good idea to have this and channelDisconnected in
    // a synchro block since terminate is called from a different
    // thread than channelDisconnected which can lead to NPE after
    // this first check!
    if (this.channel == null) {
      return;
    }

    this.terminate = true;
    if (this.channel.isConnected()) {
      this.channel.close();
    }
  }

  // ...
}

Now your listener can attempt to reconnect the exact same handler by either
creating a new pipeline with the same handler in place or access the
pipeline of the handler that just disconnected and create a new bootstrap
with it, thus reusing the same handler (which will be using a different
Channel in each connection).

You'll probably want to add more methods to YourHandler interface, but this
solves the reconnection-with-context problem.


Cheers,
  Bruno
-- 
View this message in context: http://netty-forums-and-mailing-lists.685743.n2.nabble.com/Reconnecting-a-client-automatically-without-losing-state-tp5362517p5364196.html
Sent from the Netty User Group mailing list archive at Nabble.com.


More information about the netty-users mailing list