96
votes

How to send websocket message from server to specific user only?

My webapp has spring security setup and uses websocket. I'm encountering tricky problem trying to send message from server to specific user only.

My understanding from reading the manual is from the server we can do

simpMessagingTemplate.convertAndSend("/user/{username}/reply", reply);

And on the client side:

stompClient.subscribe('/user/reply', handler);

But I could never get the subscription callback invoked. I have tried many different path but no luck.

If I send it to /topic/reply it works but all other connected users will receive it too.

To illustrate the problem I've created this small project on github: https://github.com/gerrytan/wsproblem

Steps to reproduce:

1) Clone and build the project (make sure you're using jdk 1.7 and maven 3.1)

$ git clone https://github.com/gerrytan/wsproblem.git
$ cd wsproblem
$ mvn jetty:run

2) Navigate to http://localhost:8080, login using either bob/test or jim/test

3) Click "Request user specific msg". Expected: a message "hello {username}" is displayed next to "Received Message To Me Only" for this user only, Actual: nothing is received

5
Have you been looking at convertAndSendToUser(String user, String destination, T message) ? docs.spring.io/spring/docs/4.0.0.M3/javadoc-api/org/…Viktor K.
Yes tried that too but no luckgerrytan
I've been working on private project and this is the method that we use and it is working for us. I think that one potential problem could be that you subscribe to "/user/reply" and you are sending messages to "/user/{username}/reply". I think that you should remove the {username} part and use the convertAndSendToUser(String user, String destination, T message).Viktor K.
Thanks but I tried simpMessagingTemplate.convertAndSendToUser(principal.getName(), "/user/reply", reply); and when the message is sent from server it throws this exception java.lang.IllegalArgumentException: Expected destination pattern "/principal/{userId}/**"gerrytan
@ViktorK. is right, and you were quite close to the right solution. Your subscription on client side was correct, you simply had to try: convertAndSendToUser(principal.getName(), "/reply", reply);Tip-Sy

5 Answers

89
votes

Oh, client side no need to known about current user, server will do that for you.

On server side, using following way to send message to an user:

simpMessagingTemplate.convertAndSendToUser(username, "/queue/reply", message);

Note: Using queue, not topic, Spring always using queue with sendToUser

On client side

stompClient.subscribe("/user/queue/reply", handler);

Explain

When any websocket connection is open, Spring will assign it a session id (not HttpSession, assign per connection). And when your client subscribe to an channel start with /user/, eg: /user/queue/reply, your server instance will subscribe to a queue named queue/reply-user[session id]

When use send message to user, eg: username is admin You will write simpMessagingTemplate.convertAndSendToUser("admin", "/queue/reply", message);

Spring will determine which session id mapped to user admin. Eg: It found two session wsxedc123 and thnujm456, Spring will translate it to 2 destination queue/reply-userwsxedc123 and queue/reply-userthnujm456, and it send your message with 2 destinations to your message broker.

The message broker receive the messages and provide it back to your server instance that holding session corresponding to each session (WebSocket sessions can be hold by one or more server). Spring will translate the message to destination (eg: user/queue/reply) and session id (eg: wsxedc123). Then, it send the message to corresponding Websocket session

36
votes

Ah I found what my problem was. First I didn't register the /user prefix on the simple broker

<websocket:simple-broker prefix="/topic,/user" />

Then I don't need the extra /user prefix when sending:

convertAndSendToUser(principal.getName(), "/reply", reply);

Spring will automatically prepend "/user/" + principal.getName() to the destination, hence it resolves into "/user/bob/reply".

This also means in javascript I had to subscribe to different address per user

stompClient.subscribe('/user/' + userName + '/reply,...) 
3
votes

I created a sample websocket project using STOMP as well. What I am noticing is that

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
    config.enableSimpleBroker("/topic", "/queue");// including /user also works
    config.setApplicationDestinationPrefixes("/app");
}

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

}

it works whether or not "/user" is included in config.enableSimpleBroker(...

2
votes

My solution of that based on Thanh Nguyen Van's best explanation, but in addition I have configured MessageBrokerRegistry:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/queue/", "/topic/");
        ...
    }
    ...
}
2
votes

Exactly i did the same and it is working without using user

@Configuration
@EnableWebSocketMessageBroker  
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
       registry.addEndpoint("/gs-guide-websocket").withSockJS();
    }

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