I'm trying to implement a push notification in spring using websocket and with the use of sock.js.
These are the code snippets:
public class NotifyController {
@MessageMapping("/notifications")
@SendTo("/get/notifications")
public Greeting greeting(HelloMessage message) throws Exception {
new Greeting("Hello, " + message.getName() + "!");
}
}
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/get/notifications");
config.setApplicationDestinationPrefixes("/gssocket");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/notifications").withSockJS();
}
}
This is the code in the front..
function connect() {
var notificationSocket = new SockJS('/notifications');
stompNotificationClient = Stomp.over(notificationSocket);
stompNotificationClient.connect({}, function(frame) {
console.log('Connected: ' + frame);
stompNotificationClient.subscribe('/get/notifications', function(greeting){
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function sendNotification() {
var name = "test"
stompNotificationClient.send("/gssocket/notifications", {}, JSON.stringify({ 'name': name }));
}
I've already managed to make it work. But the question is, how can I push the message to certain target users. For example, there are 5 online users namely: user1, user2, user3, user4 and user5. I want the notification to be published to user1 and user2 only. Can you give me any idea on how to achieve this one? I'm thinking of either doing it in the backend or in the frontend. Or there is another way to achieve this using spring.
Somebody help me please.
Thank you.
Messages sent by the server to the client can include plain text messages, binary data, or images. Whenever data is sent, the onmessage function is fired. This event acts as a client's ear to the server. Whenever the server sends data, the onmessage event gets fired.
The client-side WebSocket object has a . send() method that is used to send a message from the client to the server over the WebSocket connection between them. This . send() method accepts a single argument: the data to be sent to the server.
Websocket client connections may drop due to intermittent network issue and when connections drop, messages will also be lost.
You can check User destinations to target specific users with your messages, this is done using the SimpMessagingTemplate.convertAndSendToUser() call.
Note that to enable this functionality your users must be HTTP authenticated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With