Video in progress
How do convertAndSendToUser() and @SendToUser deliver a message to exactly the right user?
Spring has a UserDestinationMessageHandler: it translates an address like /user/{name}/queue/x into a unique destination for each of that user's sessions (for example /queue/x-user{sessionId}). For this to work, the Principal must be established when the connection is made.
📖 Answer
The client subscribes to its own queue:
client.subscribe('/user/queue/notifications', m => toast(m.body));
The server, from anywhere:
messaging.convertAndSendToUser("ali@example.uz", "/queue/notifications", dto);
What happens inside: Spring finds the sessions ali@example.uz currently has open (three, if there are three tabs) and sends the message to each one separately. Even if another user subscribes to /user/queue/notifications, their subscription maps to a different internal name and they won't see Ali's message.
The most common problem: no message arrives because the Principal is null. Then Spring doesn't know the user, and convertAndSendToUser finds nobody. The cause is usually that the token was validated in STOMP CONNECT, but accessor.setUser(auth) was never called.
One more nuance: the first argument is whatever Principal.getName() returns. If yours is the email and you pass a user ID, the message silently disappears.
@SendToUser("/queue/reply") replies to the user who sent the request; with broadcast = false, only to the session the request came from.
Sign up to mark studied questions and save your progress.