freakybit
freakybit

Reputation: 59

Disabling broadcast in SimpMessageTemplate.sentToUser(...) in Spring 4.2.4

I am trying to connect in two sessions with the same Spring Security user and subscribe to the same queue using Spring 4.2.4. I would like to get separate messages for each session. It's easy to do using @SendToUser, but seems that it's not so trivial when using SimpMessagingTemplate.sendToUser(...) - every session receives all messages that are specific to other session.

Example for @SendToUser:

@Controller
public class TestController {

    @MessageMapping("/queue/hello")
    @SendToUser(value = "/queue/hello", broadcast = false)
    public String test() {
        return Integer.toString(new Random().nextInt());
    }

}

Example for SimpMessagingTemplate:

template.convertAndSendToUser("SessionUser{id=123}", "/queue/hello", "test");

I've tried adding sessionId in headers as suggested for example in this thread: sending-error-message-in-spring-websockets Unfortunately it does not help in this version of Spring. Does anyone have any ideas?

Upvotes: 0

Views: 694

Answers (1)

freakybit
freakybit

Reputation: 59

Seems that setting session id in headers still works, but it has to be simpSessionId, not sessionId. My assumptions as to where the problem lies were all wrong. To summarize, we can use this overloaded method:

simpMessagingTemplate.convertAndSendToUser("SessionUser{id=123}", "/queue/hello", "test", headers);

where headers are created by:

private MessageHeaders createHeaders(String sessionId) {
    SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
    headerAccessor.setSessionId(sessionId);
    headerAccessor.setLeaveMutable(true);
    return headerAccessor.getMessageHeaders();
}

and to access simpSessionId we should use:

SimpMessageHeaderAccessor.getSessionId(message.getHeaders())

Hope this is useful for someone.

Upvotes: 1

Related Questions