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()
.
You can use SimpUserRegistry
and its getUserCount()
method instead of handling connections manually.
Example:
@Autowired
private SimpUserRegistry simpUserRegistry;
public int getNumberOfSessions() {
return simpUserRegistry.getUserCount();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With