I am working with Spring websocket implementation. For sending a message to clients, there are two ways:
1) Using @SendToUser
annotation
2) Using convertAndSendToUser
method of SimpMessagingTemplate
@SendToUser
takes a boolean parameter called broadcast
which if set to false publishes the message to the current session. Is there a way I can have this behaviour in SimpMessagingTemplate
.
If we take a look to the SendToMethodReturnValueHandler
source code, we'll see:
if (broadcast) {
this.messagingTemplate.convertAndSendToUser(user, destination, returnValue);
}
else {
this.messagingTemplate.convertAndSendToUser(user, destination, returnValue, createHeaders(sessionId));
}
So, what you need for your use-case just use that overloaded convertAndSendToUser
and provide a Map
with `sessionId:
messagingTemplate.convertAndSendToUser(user, destination, payload,
Collections.singletonMap(SimpMessageHeaderAccessor.SESSION_ID_HEADER, sessionId))
Spring doesn't have a clear document, I tried many different way, only below code works for me.
SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create();
accessor.setHeader(SimpMessageHeaderAccessor.SESSION_ID_HEADER, sessionId);
messagingTemplate.convertAndSendToUser(sessionId, destination, payload, accessor.getMessageHeaders());
The answer above did not work for me. It turns out that with Spring 4.1.4 something slightly different is required.
The way that seems the cleanest to me looks like the following:
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create();
headerAccessor.setSessionId(cmd.getSessionId());
headerAccessor.setLeaveMutable(true);
MessageHeaders messageHeaders = headerAccessor.getMessageHeaders();
messagingTemplate.convertAndSendToUser(cmd.getPrincipal().getName(),
"/queue/responses", ret, messageHeaders);
The other way which worked was to explicitly add a "nativeHeaders" value to the Map sent to SimpMessagingTemplate.convertAndSendToUser(). However, this way seems to depend too much on implementation details:
Map<String, Object> headers = new HashMap<>();
headers.put("nativeHeaders", new HashMap<String, Object>());
headers.put(SimpMessageHeaderAccessor.SESSION_ID_HEADER, cmd.getSessionId());
messagingTemplate.convertAndSendToUser(cmd.getPrincipal().getName(),
"/queue/responses", ret, headers);
The "offending code" which made setting the "simpSessionId" header and nothing else in a Map not work was in SimpMessagingTemplate.processHeaders() and MessageHeaderAccessor.getAccessor(MessageHeaders, Class requiredType).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With