Home > Software engineering >  Is there a way to get a list of all users subscribed to a topic?
Is there a way to get a list of all users subscribed to a topic?

Time:02-03

I'm making a WebSocket Chat application in Spring Boot and i want to display a list of all connected users, is it possible to write some sort of function that retrieves all connected users?

Here is my WebSocketConfig:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat-example").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app");
        registry.enableSimpleBroker("/topic");
    }
}

And here is the controller:

@Controller
public class ChatController {
    private final MessageRepository messageRepository;

    public ChatController(MessageRepository messageRepository) {
        this.messageRepository = messageRepository;
    }

    @MessageMapping("/chat.send")
    @SendTo("/topic/public")
    public ChatMessage sendMessage(@Payload ChatMessage chatMessage) {
        messageRepository.save(chatMessage);
        return chatMessage;
    }

    @MessageMapping("chat.newUser")
    @SendTo("/topic/public")
    public ChatMessage newUser(@Payload ChatMessage chatMessage, SimpMessageHeaderAccessor headerAccessor) {
        headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
        messageRepository.save(chatMessage);
        return chatMessage;
    }
}

CodePudding user response:

you can store the connected user sessions in a data structure, such as a Set, and update it whenever a user connects or disconnects.

private static final Map<String, String> connectedUsers = new ConcurrentHashMap<>();

@MessageMapping("/chat.newUser")
@SendTo("/topic/public")
public ChatMessage newUser(@Payload ChatMessage chatMessage,    SimpMessageHeaderAccessor headerAccessor) {
String sessionId = headerAccessor.getSessionId();
String username = chatMessage.getSender();
connectedUsers.put(sessionId, username);
headerAccessor.getSessionAttributes().put("username", username);
messageRepository.save(chatMessage);
return chatMessage;
}

@GetMapping("/connected-users")
public List<String> connectedUsers() {
return new ArrayList<>(connectedUsers.values());
}
  • Related