亲爱的, 我试图在我的WebSocketHandler中获取一个HTTPSession。当我使用'javax.websocket-api'时我可以成功完成操作,但是现在使用'Spring-Websocket'。
配置:
@ConditionalOnWebApplication
@Configuration
@EnableWebSocket
public class WebSocketConfigurator implements WebSocketConfigurer {
@Autowired
private ApplicationContext context;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
MyEndpoint endpoint = context.getBean(MyEndpoint.class);
registry.addHandler(endpoint, "/signaling");
}
}
建立连接后:
@Component
public class MyEndpoint implements WebSocketHandler {
private WebSocketSession wsSession;
@Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
this.wsSession = webSocketSession;
// need to get the HTTP SESSION HERE
log.info("Opening: " + webSocketSession.getId());
}
}
现在这是我如何使用'javax.websocket-api'做到这一点的示例:
配置:
@ServerEndpoint(value = "/signaling", //
decoders = MessageDecoder.class, //
encoders = MessageEncoder.class,
configurator = MyEndpointConfigurator.class)
/***
* define signaling endpoint
*/
public class MyEndpoint extends NextRTCEndpoint {
}
然后我注入了HTTPSession来修改握手:
public class MyEndpointConfigurator extends ServerEndpointConfig.Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig config,
HandshakeRequest request,
HandshakeResponse response) {
HttpSession httpSession = (HttpSession) request.getHttpSession();
config.getUserProperties().put(HttpSession.class.getName(), httpSession);
}
}
最后,当建立WS连接时可以访问它:
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
this.wsSession = session;
this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
log.info("Opening: " + session.getId());
server.register(session, httpSession);
}
我无法成功完成与“ Spring Websocket”类似的操作。有什么办法吗?请不要从StompJS提出类,因为我没有使用它。
答案 0 :(得分:2)
有一个可以使用的
**
* An interceptor to copy information from the HTTP session to the "handshake
* attributes" map to made available via{@link WebSocketSession#getAttributes()}.
*
* <p>Copies a subset or all HTTP session attributes and/or the HTTP session id
* under the key {@link #HTTP_SESSION_ID_ATTR_NAME}.
*
* @author Rossen Stoyanchev
* @since 4.0
*/
public class HttpSessionHandshakeInterceptor implements HandshakeInterceptor {
Reference Manual中有一个示例如何配置它:
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyHandler(), "/myHandler")
.addInterceptors(new HttpSessionHandshakeInterceptor());
}
因此,无论您在HTTP会话中需要什么,都可以在WebSocketSession.getAttributes()
中找到。