Spring WebSocket ConvertAndSendToUser not working but convertAndSend working

Viewed 4091

I am new to Spring boot websocket and messaging semantics. Currently i am able to send private messages using the below code.

String queueName = "/user/" + username  + "/queue/wishes";
simpMessagingTemplate.convertAndSend(queueName, message);

When trying to use convertAndSendToUser I am not getting any error but the message is not getting sent. I knew that with sendToUser there should be a slight change in how the destination name should be formed but I am not getting it right.

String queueName = "/user/queue/wishes";
simpMessagingTemplate.convertAndSendToUser(username, queueName, message);

Below is my subscription code.

stompClient.subscribe('/user/queue/wishes', function(message) {
    alert(message);
}) 
4 Answers

I had a similar problem, if your username is actually a sessionId, then try to use one of the overloaded methods that accept headers (so said in SimpMessageSendingOperations javadoc):

SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
headerAccessor.setSessionId(username);
headerAccessor.setLeaveMutable(true);

messagingTemplate.convertAndSendToUser(username, "/queue/wishes", message, headerAccessor.getMessageHeaders());

my example

It is not getting sent because your "destination" i.e "queuename" is incorrect. As you can see here SimpMessagingTemplate.java#L230 this is the method that gets invoked as a part of the chain on invocations of template.convertAndSendToUser().

This method already prefixes /user to the final destination. So instead you should do something like this: simpMessagingTemplate.convertAndSendToUser(username,"/queue/wishes", message); Now with the correct destination it should get sent to user.

Finally figured out the problem. I did a silly mistake. I was filling the User DestinationPrefix as part of WebSocket config. but didn't set it up for the injected bean SimpMessaging template.

You must registry the prefix of SimpleBroker:

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

Although the UserDestinationPrefix has been set for default value "/user/", you must to add the SimpleBroker prefix.

Related