I have a simple spring application with websocket functionality and everything works so far. Now I want to send a message from my server to a specific client using the @Send
Building on Biju's answer and using the Stomp generated session id (thanks, mariusz2108 in his answer to a similar question), here's what worked for me (based on the canonical example from Spring)
SpringFramework client:
private SimpMessagingTemplate template;
@Autowired
public GreetingController(SimpMessagingTemplate template) {
this.template = template;
}
@MessageMapping("/hello")
public void greeting(HelloMessage message, @Header("simpSessionId") String sessionId) throws Exception {
template.convertAndSend("/queue/greeting-"+sessionId, new Greeting("Hello, " + message.getName()));
}
JavaScript client:
function connect() {
var socket = new SockJS('/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
var sessionId = /\/([^\/]+)\/websocket/.exec(socket._transport.url)[1];
console.log("connected, session id: " + sessionId);
stompClient.subscribe('/queue/greeting-'+sessionId, function (greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
});
}
Instead of the Stomp session id you could use your web container's Session ID (e.g. JSESSIONID) but now that cookie is not by default accessible from JavaScript (for Tomcat) this is a more difficult prospect.