Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() .

like image 468
Leander Gilles Avatar asked Sep 24 '16 14:09

Leander Gilles


1 Answers

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

Example:

@Autowired
private SimpUserRegistry simpUserRegistry;

public int getNumberOfSessions() {
    return simpUserRegistry.getUserCount();
}
like image 116
Abdullah Gürsu Avatar answered Oct 04 '22 08:10

Abdullah Gürsu