2017-02-15 10 views
2

Java SpringでセッションIDを取得する方法WebSocketStompClient?Spring WebSocketStompClientでセッションIDを取得するには?

WebSocketStompClientとStompSessionHandlerAdapterがあります。これらのインスタンスはサーバーのwebsocketに正常に接続します。 WebSocketStompClientはSockJsClientを使用します。
しかし、websocket接続のセッションIDを取得する方法がわかりません。クライアント側のストンプセッションハンドラを持つコードで

private class ProducerStompSessionHandler extends StompSessionHandlerAdapter { 
      ... 
      @Override 
      public void afterConnected(StompSession session, StompHeaders connectedHeaders) { 
      ... 
      } 

stompセッションには、サーバー上のセッションIDとは異なるセッションIDが含まれています。したがって、このIDSから :

DEBUG ... Processing SockJS open frame in WebSocketClientSockJsSession[id='d6aaeacf90b84278b358528e7d96454a... 

DEBUG ... DefaultStompSession - Connection established in session id=42e95c88-cbc9-642d-2ff9-e5c98fb85754 

私はWebSocketClientSockJsSessionから、最初のセッションIDが必要です。 しかし、私はあなたが以下のように独自のインターセプタを定義し、カスタム属性としてセッションIDを設定する必要があり、セッションIDを取得するには... WebSocketStompClientまたはSockJsClientに

答えて

2

をセッションIDのようなものを取得するための任意の方法が見つかりませんでした。

public class HttpHandshakeInterceptor implements HandshakeInterceptor { 

    @Override 
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, 
      Map attributes) throws Exception { 
     if (request instanceof ServletServerHttpRequest) { 
      ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request; 
      HttpSession session = servletRequest.getServletRequest().getSession(); 
      attributes.put("sessionId", session.getId()); 
     } 
     return true; 
    } 

これで、コントローラクラスで同じセッションIDを取得できます。

@MessageMapping("/message") 
public void processMessageFromClient(@Payload String message, SimpMessageHeaderAccessor headerAccessor) throws Exception { 
     String sessionId = headerAccessor.getSessionAttributes().get("sessionId").toString(); 

    } 

参考: Maintaining spring session with stomp websocket

+0

ありがとうございます!サーバーがjavascriptクライアントでも動作するため、その要求によってJavaクライアントにセッションIDを送信します。 – Irina

+0

独自のインターセプタを作成する代わりに、組み込みの['HttpSessionHandshakeInterceptor'](https://docs.spring.io/spring-framework/docs/5.0.0.RELEASE/javadoc-api/org/)を使用することができます。 springframework/web/socket/server/support/HttpSessionHandshakeInterceptor.html)を参照してください。 – izstas

関連する問題