title: Spring websocket - how to get number of sessions
body: <p>I'm using <a href="https://spring.io/guides/gs/messaging-stomp-websocket/" rel="noreferrer">this</a> tutorial and I'm trying to figure out how to get the number of current sessions.</p>
  
  <p>My WebSocketConfig looks like this (copy and paste from the tutorial) :</p>
  
  <pre><code>@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();
      }
  
  }
  </code></pre>
  
  <p>I'd like to know the number of sessions inside of this class (again copy and paste):</p>
  
  <pre><code>@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() + "!");
      }
  
  }
  </code></pre>
  
  <p>Is there an easy way to get the number of current sessions(users, connections) to the websocket?</p>
  
  <p>Edit:</p>
  
  <p><strong>Here is my solution:</strong></p>
  
  <pre><code>Set&lt;String&gt; mySet = Collections.newSetFromMap(new ConcurrentHashMap&lt;String, Boolean&gt;());
  
  @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());
  }
  </code></pre>
  
  <p>I can now get the number of Sessions with <code>mySet.size()</code> .</p>