java - 在 WebSocketHandler 中访问 HTTP 会话(Spring-websocket)
问题描述
亲爱的,我正在尝试在我的 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 提出课程,因为我没有使用它。
解决方案
有这个可以使用:
**
* 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 {
参考手册中有一个示例如何配置它:
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyHandler(), "/myHandler")
.addInterceptors(new HttpSessionHandshakeInterceptor());
}
因此,您从 HTTP 会话中需要的任何内容都将在WebSocketSession.getAttributes()
.
推荐阅读
- javascript - EJS - 包含来自 JSON 文件的配置
- javascript - 如何检查空数组的对象
- node.js - 如何以与前缀字段绑定的角度方式向数组添加新属性
- reactjs - 使用 antd 输入组件放大 npx create-react-app 中的输入搜索组件
- swift - 如何在会话运行期间修改“AR参考图像集”?
- python - 使用函数过滤行而不是创建单独的数据帧副本
- html - 在 React 中在不更改视口的情况下在顶部渲染 html?
- java - 如何将文件中的文本行存储到数组中并在java中的所需位置打印行?
- arrays - 对两个 Ruby 多维数组进行计算
- hyperparameters - GPflow 中超参数的初步猜测