How to get all clients subscribed on websocket

浪子不回头ぞ 提交于 2020-01-25 06:41:18

问题


I have a websocket connection made in SpringBoot Stomp, and I need to get all users connected to this socket every time a new subscriber comes up, I tried using the method

defaultSimpUserRegistry.getUsers()

but to no avail, returns an empty list even though 1 user is logged in.

@Component
public class SubscribeEventListener implements ApplicationListener<SessionSubscribeEvent> {

@Autowired
SimpMessagingTemplate simpMessagingTemplate;

@Override
public void onApplicationEvent(SessionSubscribeEvent sessionSubscribeEvent) {
    final DefaultSimpUserRegistry defaultSimpUserRegistry = new DefaultSimpUserRegistry();
    System.out.println(defaultSimpUserRegistry.getUsers());

    StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(sessionSubscribeEvent.getMessage());

    simpMessagingTemplate.convertAndSend("/home", headerAccessor.getNativeHeader("name").get(0));
 }
}

SimpMessagingTemplate is correctly returning the passed client header to websocket for all clients.

Config websocket

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/ws").setAllowedOrigins("*");
}

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

来源:https://stackoverflow.com/questions/58925128/how-to-get-all-clients-subscribed-on-websocket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!