Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring WebSocket ConvertAndSendToUser not working but convertAndSend working

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);
}) 
like image 782
Harsha Avatar asked Oct 28 '25 13:10

Harsha


2 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

like image 149
xDrake Avatar answered Oct 31 '25 04:10

xDrake


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.

like image 26
user17782565 Avatar answered Oct 31 '25 06:10

user17782565