Reputation: 1
@EventListener
public void handleWebSocketSubscribeListener(SessionSubscribeEvent event) {
StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
final Long chattingRoomId = Long.valueOf(headerAccessor.getSubscriptionId());
final String loginId = headerAccessor.getUser().getName();
chattingRoomConnectService.connectChattingRoom(chattingRoomId,loginId,headerAccessor.getSessionId());
chattingService.sendEnterMessage(chattingRoomId,loginId);
chattingService.updateCountAllZero(chattingRoomId,loginId);
headerAccessor.getSessionAttributes().put(SUB,chattingRoomId);
}
I want to send the "Enter Message" to subscribed Chatting Room after Subscribe, but the code above seems to send a message merely based on the client's request even before the subscription is actually completed rather than after the subscription has been established.
I considered using @SubscribeMapping
along with a return, but the message was only sent to the client that made the subscription request.
I just need something like SubscribedEvent
.
Can you give me some advice?
Upvotes: 0
Views: 31
Reputation: 11
The @SubscribeMapping
annotation by default sends the return value to the user. However, by using annotations such as @SendTo
or utilizing SimpMessagingTemplate, you can directly specify the topic endpoint where the message should be sent.
You could write the Controller class like this:
private final SimpMessagingTemplate messagingTemplate;
...
@SubscribeMapping("/chat/{chattingRoomId}")
@SendTo("/topic/chat/{chattingRoomId}")
public void handleSubscription(@DestinationVariable Long chattingRoomId, StompHeaderAccessor headerAccessor) {
String loginId = headerAccessor.getUser().getName();
return loginId + " has entered the room!";
}
Or like this:
private final SimpMessagingTemplate messagingTemplate;
...
@SubscribeMapping("/chat/{chattingRoomId}")
public void handleSubscription(@DestinationVariable Long chattingRoomId, StompHeaderAccessor headerAccessor) {
String loginId = headerAccessor.getUser().getName();
messagingTemplate.convertAndSend("/topic/chat/" + chattingRoomId, loginId + " has entered the room!");
}
Upvotes: 1