Leander Gilles
Leander Gilles

Reputation: 223

Spring websocket - how to get number of sessions

I'm using this tutorial and I'm trying to figure out how to get the number of current sessions.

My WebSocketConfig looks like this (copy and paste from the tutorial) :

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-guide-websocket").withSockJS();
    }

}

I'd like to know the number of sessions inside of this class (again copy and paste):

@Controller
public class GreetingController {


    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        Thread.sleep(1000); // simulated delay
        return new Greeting("Hello, " + message.getName() + "!");
    }

}

Is there an easy way to get the number of current sessions(users, connections) to the websocket?

Edit:

Here is my solution:

Set<String> mySet = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());

@EventListener
private void onSessionConnectedEvent(SessionConnectedEvent event) {
    StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
    mySet.add(sha.getSessionId());
}

@EventListener
private void onSessionDisconnectEvent(SessionDisconnectEvent event) {
    StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
    mySet.remove(sha.getSessionId());
}

I can now get the number of Sessions with mySet.size() .

Upvotes: 11

Views: 18117

Answers (2)

Mirjalol Bahodirov
Mirjalol Bahodirov

Reputation: 2541

You can use ApplicationContext events. Every connection, subscription or other action will fire a special event: SessionConnectEvent, SessionConnectedEvent, SessionSubscribeEvent and so on.

Full doc is here. When one of these events fires, you can handle it with your own logic.

Sample code for reference:

@EventListener(SessionConnectEvent.class)
public void handleWebsocketConnectListner(SessionConnectEvent event) {
    logger.info("Received a new web socket connection : " + now());
}

@EventListener(SessionDisconnectEvent.class)
public void handleWebsocketDisconnectListner(SessionDisconnectEvent event) {
    logger.info("session closed : " + now());
}

Upvotes: 12

Abdullah G&#252;rsu
Abdullah G&#252;rsu

Reputation: 3186

You can use SimpUserRegistry and its getUserCount() method instead of handling connections manually.

Example:

@Autowired
private SimpUserRegistry simpUserRegistry;

public int getNumberOfSessions() {
    return simpUserRegistry.getUserCount();
}

Upvotes: 23

Related Questions