Skip to content

Connection state listeners

bristleback edited this page May 19, 2013 · 5 revisions

Connection state listeners are used to perform additional operations when user connection state changes. Currently, connecting and disconnecting events can be handled. Multiple listeners may be defined and order of their execution can be determined using Spring Framework @Order annotation.

A listener interface ConnectionStateListener is parametrized and contains two methods, both taking UserContext implementation as parameters:

    public interface ConnectionStateListener<T extends UserContext> {
    
      void userConnected(T userContext, ConnectionStateListenerChain connectionStateListenerChain);
    
      void userDisconnected(T userContext, ConnectionStateListenerChain connectionStateListenerChain);
    }

An userConnected() method is called after user is connected and added to the users container. That means, this user can receive messages (listener is able to send messages to this user) and will be included in recipients list when a broadcast messages is being sent to all connected users.

Second method, userDisconnected(), is called by the server engine AFTER user is disconnected from the server. In this case, user cannot receive any further messages and won't be included in recipients list.

Defining custom listeners is a simple task, you just need to create a class implementing ConnectionStateListener interface and define it as a Spring bean. Bristleback will automatically discover all defined listeners.

    @Component
    public class ChatConnectionStateListener implements ConnectionStateListener<BaseUserContext> {
    
      @Autowired
      private SampleClientActionClass sampleClientClass;
    
      @Override
      public void userConnected(BaseUserContext user, ConnectionStateListenerChain connectionStateListenerChain) {
        // logic here
      }
    
      @Override
      public void userDisconnected(BaseUserContext user, ConnectionStateListenerChain connectionStateListenerChain) {
        // logic here
      }
    }

ConnectionStateListenerChain object

Both connection state listener methods have ConnectionStateListenerChain parameter. This parameter can be used to cancel remaining connection state listeners execution.