As this quetion, I want to send to a specific user with its sessionID.
And I try the answer's solution but the client side still not receiving the message.
These are my setting.
I save user's sessionID when they connect to the server
@EventListener
private void handleSessionConnected(SessionConnectEvent event) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(event.getMessage());
String username = headers.getNativeHeader("login").get(0);
String sessionId = headers.getSessionId();
User user = new User(username, sessionId);
participantRepository.add(user);
Success", headers.getMessageHeaders());
}
The broadcast message handler in Controller
@MessageMapping("/chat")
public void handleChat(ChatMessage message, SimpMessageHeaderAccessor headerAccessor) throws Exception{
logger.debug(">>>[CHAT MESSAGE]");
JsonParser parser = new JsonParser();
String jsonMessage = gson.toJson(message);
JsonObject jsonObMessage =
parser.parse(jsonMessage).getAsJsonObject().get("map").getAsJsonObject();
messagingTemplate.convertAndSend("/queue", message);
}
The private message handler in Controller
@MessageMapping("/chat.{user}")
public void handlePrivateChat(@Payload ChatMessage message, SimpMessageHeaderAccessor headerAccessor) throws Exception{
logger.debug(">>>[PRIVATE CHAT MESSAGE]");
JsonParser parser = new JsonParser();
SimpMessageHeaderAccessor responseAccessor = SimpMessageHeaderAccessor
.create(SimpMessageType.MESSAGE);
String jsonMessage = gson.toJson(message);
JsonObject jsonObMessage =
parser.parse(jsonMessage).getAsJsonObject().get("map").getAsJsonObject();
User toUser = activeUsers.getByName(jsonObMessage.get("to").getAsString());
String destinateSessionID = toUser.getSessionID();
responseAccessor.setSessionId(destinateSessionID);
responseAccessor.setLeaveMutable(true);
MessageHeaders responseMessageHeader = responseAccessor.getMessageHeaders();
if(toUser != null){
messagingTemplate.convertAndSendToUser(destinateSessionID, "/queue", message, responseMessageHeader);
}
}
Both message handler could get the message but the client could only get the broadcast message. Still couldn't find the answer. Hope someone could help me. Thx.
Update
In my WebSocketConfig
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/queue", "/topic");
registry.setApplicationDestinationPrefixes("/app");
}