例如:如果我正在为某些商品进行拍卖,那么我需要为每个auctionId生成单独的WebSocketHandler实例。 我们可以附上" auctionId"作为url的路径参数,以便为不同的拍卖生成不同的实例?
或者还有其他方法可以达到这个目的吗?
这就是我添加处理程序的方式:
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(websocketTestHandler(), "/websocket-test");
}
答案 0 :(得分:6)
如果您想使用TextWebSocketHandler
,则可以将竞价ID作为网址路径的一部分传递。您必须在握手期间将路径复制到WebSocket会话(这是您可以访问ServerHttpRequest
的唯一地方,因为握手是一个http请求),然后从您的处理程序中检索属性。
以下是实施:
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(auctionHandler(), "/auction/*")
.addInterceptors(auctionInterceptor());
}
@Bean
public HandshakeInterceptor auctionInterceptor() {
return new HandshakeInterceptor() {
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
// Get the URI segment corresponding to the auction id during handshake
String path = request.getURI().getPath();
String auctionId = path.substring(path.lastIndexOf('/') + 1);
// This will be added to the websocket session
attributes.put("auctionId", auctionId);
return true;
}
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Exception exception) {
// Nothing to do after handshake
}
};
}
@Bean
public WebSocketHandler auctionHandler() {
return new TextWebSocketHandler() {
public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
// Retrieve the auction id from the websocket session (copied during the handshake)
String auctionId = (String) session.getAttributes().get("auctionId");
// Your business logic...
}
};
}
}
<强>客户端:强>
new WebSocket('ws://localhost:8080/auction/1');
即使这是一个有效的解决方案,我建议你看看STOMP over WebSockets,它会给你更多的灵活性。
答案 1 :(得分:1)
另一种选择是从会话URI中获取值。
请参见下面的示例,其中我会检查会话中是否包含Box值。
URI就像/ chat / {box}
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws IOException {
Map<String, String> value = new Gson().fromJson(message.getPayload(), Map.class);
String sender = value.get("sender");
String content = value.get("content");
String box = value.get("box");
for (WebSocketSession webSocketSession : sessions) {
LOGGER.info("Get messages on box {} and URI {}", box, session.getUri().toString());
if (webSocketSession.getUri().toString().contains(box)) {
webSocketSession.sendMessage(new TextMessage(sender + ": " + content + " !"));
}
}
}
在这种情况下,您不需要拦截器。