Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get Session in Spring Controller when using Websockets

I am using Websockets SockJS with Spring MVC Framework. I tried the Stock Ticker example that's working fine but now I want to get Session in my Controller but I am unable to find a way out.

Client Code:
$scope.socket = new SockJS("ws/ws"); 
$scope.stompClient = Stomp.over($scope.socket); 
$scope.stompClient.connect("guest", "guest",connectCallback, errorCallback);

//in connectCallback
$scope.stompClient.subscribe('/topic/agent-sendstatus', showScreenPop);

    Java Code:
    @MessageMapping("/topic/agent-sendstatus")
        public void testmethod()
        {
            //How do i get Session here to further implement solution?

            template.convertAndSend("/topic/agent-sendstatus","bcd");
        }

Please suggest.
like image 807
abcd Avatar asked Dec 26 '22 04:12

abcd


1 Answers

In case you are referring to the WebSocket session, Spring 4.1 lets you get the session attributes in a header of the incoming client messages which can be accessed via the SimpMessageHeaderAccessor.

@MessageMapping("/topic/agent-sendstatus")
public void testmethod(SimpMessageHeaderAccessor headerAccessor) {
    String sessionId = headerAccessor.getSessionId(); // Session ID
    Map<String, Object> attrs = headerAccessor.getSessionAttributes(); // Session Attributes
    ...
}
like image 63
Sergi Almar Avatar answered Jan 05 '23 10:01

Sergi Almar