Send private message with @SendToUser annotation in Spring WebSocket

In the tutorial showing you how to implement WebSocket with Spring WebSocket, my example application will allow all clients to receive all messages when they subscribe to the endpoint, and in the tutorial about sending messages to a specific user, my example application allows the client to send a message to a user associated with a specific sessionId. A bit inconvenient here if our need is just to send a request to the WebSocket server, need it to handle the business logic and return the results for ourselves, of course you can also solve the problem by sending STOMP message as I instructed, but we also have to assign a user associated with sessionId to be able to do this. Using Spring WebSocket’s @SendToUser annotation, you will not need to assign this user information. How is it in detail? I will guide you all in this tutorial.

I also created a new Spring Boot with Web and WebSocket dependency.

The result is as follows:

Send private message with @SendToUser annotation in Spring WebSocket

I also declare to use WebJars with JQuerySocketJS client and Stomp WebSocket dependencies as follows:

WebSocketConfiguration class to configure WebSocket:

We will use the @SendToUser annotation in the controller to handle the request message from the client as follows:

The value declared in the @SendToUser annotation is the endpoint that the client will subscribe to to receive messages from the WebSocket server!

In essence, Spring also uses an endpoint to send a message to a certain user with the default prefix “/user”. You can also change this default prefix by using the setUserDestinationPrefix() method of the MessageBrokerRegistry object in the WebSocketConfiguration class as I did in the previous post. The difference here is that instead of we need to manage the user associated with the sessionId of the WebSocket connection, now Spring will use the sessionId to only send messages to the requesting client only!

Now I’ll add the front-end code to see how our example works!

index.html:

app.js

As you can see, on the client side, we will subscribe to the endpoint with the default prefix starting with “/user” as in the previous post.

Now, if I will open 2 browser windows, enter my name in the ” What is your name” box, press the Send button, you will see that only the window I am working on receives a message from the WebSocket server:

Send private message with @SendToUser annotation in Spring WebSocket

3/5 - (1 vote)

Add Comment