Reputation: 333
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.
Upvotes: 10
Views: 7230
Reputation: 2459
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.
Upvotes: 6