Sending message to specific user on Spring Websocket

Oh, client side no need to known about current user, server will do that for you.

On server side, using following way to send message to an user:

simpMessagingTemplate.convertAndSendToUser(username, "/queue/reply", message);

Note: Using queue, not topic, Spring always using queue with sendToUser

On client side

stompClient.subscribe("/user/queue/reply", handler);

Explain

When any websocket connection is open, Spring will assign it a session id (not HttpSession, assign per connection). And when your client subscribe to an channel start with /user/, eg: /user/queue/reply, your server instance will subscribe to a queue named queue/reply-user[session id]

When use send message to user, eg: username is admin
You will write simpMessagingTemplate.convertAndSendToUser("admin", "/queue/reply", message);

Spring will determine which session id mapped to user admin. Eg: It found two session wsxedc123 and thnujm456, Spring will translate it to 2 destination queue/reply-userwsxedc123 and queue/reply-userthnujm456, and it send your message with 2 destinations to your message broker.

The message broker receive the messages and provide it back to your server instance that holding session corresponding to each session (WebSocket sessions can be hold by one or more server). Spring will translate the message to destination (eg: user/queue/reply) and session id (eg: wsxedc123). Then, it send the message to corresponding Websocket session

Leave a Comment