亲爱的,我正试着在我的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中的类,因为我没有使用它。
发布于 2018-08-09 22:13:44
这里有一个可以使用的:
**
* 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 session中需要的任何东西都将在WebSocketSession.getAttributes()中可用。
https://stackoverflow.com/questions/51757269
复制相似问题