Spring broadcast message to users via private channel

Viewed 17

I'm struggling how to send message to all users in a private channel in Spring. Here is my WebSocket config class:

    @Configuration
    @EnableWebSocketMessageBroker
    public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    
      @Override
      public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/all", "/message","/topic");
        config.setUserDestinationPrefix("/secured/user");
        config.setApplicationDestinationPrefixes("/app");
      }
    
      @Override
      public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws");
        registry.addEndpoint("/ws")
            .setHandshakeHandler(new UserHandshakeHandler())
            .withSockJS();
      }
    }

Then I have a list of all my usernames, so I loop my list to send each of them a private message, like this:

@Service
@Slf4j
public class MessageService {
  
  private final SimpMessagingTemplate simpMessagingTemplate;

  public MessageService(SimpMessagingTemplate simpMessagingTemplate) {
    this.simpMessagingTemplate = simpMessagingTemplate;
  }

  @Async
  @Scheduled(fixedDelay = 1000, initialDelay = 1000)
  public void sendMessageToUser() {
    List<String> nameList = Lists.newArrayList("admin", "user");
    for(String username : nameList){
      simpMessagingTemplate.convertAndSendToUser(username,"/message", "Hello "+username);
    }
  }
}

Then in my web frontend, I setup a websocket connection like this:

function connect() {
  const socket = new SockJS('/ws');
  stompClient = Stomp.over(socket);
  stompClient.connect({}, function (frame) {
    console.log('Connected: ' + frame);
    stompClient.subscribe('/secured/user/message',
        function (message) {
          console.log(message);
        });
  });
}

I got confirmation that frontend successfully establish the websocket connection:

Opening Web Socket...
stomp.min.js:8 Web Socket Opened...
stomp.min.js:8 >>> CONNECT
accept-version:1.1,1.0
heart-beat:10000,10000


stomp.min.js:8 <<< CONNECTED
version:1.1
heart-beat:0,0
user-name:admin


stomp.min.js:8 connected to server undefined
message.js:18 Connected: CONNECTED
user-name:admin
heart-beat:0,0
version:1.1


stomp.min.js:8 >>> SUBSCRIBE
id:sub-0
destination:/secured/user/message

The problem is the message is indeed sent from server side, but simply not able to be received in the frontend. Hugely appreciate if anyone could help spot the issue in my code. Thanks a lot!

0 Answers
Related