Spring websocket - how to get number of sessions
You can use SimpUserRegistry
and its getUserCount()
method instead of handling connections manually.
Example:
@Autowired
private SimpUserRegistry simpUserRegistry;
public int getNumberOfSessions() {
return simpUserRegistry.getUserCount();
}
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());
}