Hello fellow developers,
I recently implemented Java Spring WebSockets to send notifications in my application, the websocket communication works with convertAndSend when I send to all users but not to a specific user
WebSocket Configuration (WebSocketBrokerConfiguration.java):
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketBrokerConfiguration implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/notification");
registry.setApplicationDestinationPrefixes("/app");
}
}
Security Configuration (SecurityConfiguration.java):
.authorizeHttpRequests(authz ->
authz.requestMatchers("*/ws/**").permitAll()
Sending Notifications in Resource:
this.simpMessagingTemplate.convertAndSendToUser(
employee.getEmail(),
"/notification",
new NotificationDTO(
NotificationTypeEnum.NEW_REQUEST,
"A new request has been made"
));
Frontend Implementation (Angular - Main Component):
const stompClient: Client = this.notificationService.connect();
stompClient.connect({}, frame => {
console.log('[Websocket] Connected: ' + frame);
stompClient.subscribe('/user/notification', data => {
console.log('[Websocket] ', data);
});
});
notificationService (Angular):
connect(): Client {
const socket = new SockJs('/ws');
const stompClient = Stomp.over(socket);
return stompClient;
}
Issue Faced: The WebSocket connection appears to be established correctly, and the subscription is set up in the frontend. However, notifications sent using convertAndSendToUser are not received by the employee account that subscribed to /user/notification.
SimpMessagingTemplate#convertAndSendToUser will internally prefix "/user" (the default user destination prefix, which you can configure though) and append the username and the provided destination to it, and use that as the message destination.
So you will have to subscribe to /user/{employee-email}/notification
in your client. And also register /user
in your simpleBroker list.