Spring WebSocket @SendToSession: send message to specific session

前端 未结 3 732
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 02:49

Is it possible to send a message to specific session?

I have an unauthenticated websocket between clients and a Spring servlet. I need to send an unsolicited message

3条回答
  •  醉梦人生
    2020-11-28 02:56

    No need to create specific destinations, it's already done out of the box as of Spring 4.1 (see SPR-11309).

    Given users subscribe to a /user/queue/something queue, you can send a message to a single session with:

    As stated in the SimpMessageSendingOperations Javadoc, since your user name is actually a sessionId, you MUST set that as a header as well otherwise the DefaultUserDestinationResolver won't be able to route the message and will drop it.

    SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor
        .create(SimpMessageType.MESSAGE);
    headerAccessor.setSessionId(sessionId);
    headerAccessor.setLeaveMutable(true);
    
    messagingTemplate.convertAndSendToUser(sessionId,"/queue/something", payload, 
        headerAccessor.getMessageHeaders());
    

    You don't need users to be authenticated for this.

提交回复
热议问题