我使用经典的Spring 5 WebSocket API编写WebSocket应用程序,即不使用SockJS和STOMP。 我在获取所有活动的HTTP会话时遇到问题。 我可以得到一个当前会话,但是如何获得所有活动会话? 如果使用经典的Java API(JSR356),则使用以下方法:session.getOpenSessions()获取所有打开的会话。 但是我在Spring 5 WebSocket API中找不到类似这种方法的东西。 如何获得所有活动的会话?
//Configuration of WebSocket.
@Configuration
@EnableWebSocket
public class WebSocketConfig implements
WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
//Map endpoint URL to handler's method.
//Add interceptor of HTTP-handshake to copy HTTP-session's attributes to WebSocket-session's attributes.
registry.addHandler(getWsEndpoint(), "/endpoint").addInterceptors(new HttpSessionHandshakeInterceptor());
}
@Bean
public WebSocketHandler getWsEndpoint() {
return new WsEndpoint();
}
}
我的WebSocket端点:
// WebSocket endpoint class.
public class WsEndpoint extends TextWebSocketHandler {
public WsEndpoint(){}
public WebSocketMessage<String> wsMsg;
// This method will be called after successful websocket connection.
@Override
public void afterConnectionEstablished(WebSocketSession session)
throws java.lang.Exception {
wsMsg = new TextMessage(new String("Connection ok!"));
session.sendMessage(wsMsg);
}
// This method is called if message was recieved.
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
wsMsg = new TextMessage(new String("Message recieved!"));
session.sendMessage(wsMsg);
}
}
答案 0 :(得分:1)
SimpUserRegistry
(DefaultSimpUserRegistry
)跟踪已连接的Websocket用户。
方法getUsers()
返回所有已连接的用户及其会话。
这是示例代码:
@RestController
public class WebSocketController {
private final SimpUserRegistry simpUserRegistry;
public ScvWebSocketApiController(SimpUserRegistry simpUserRegistry) {
this.simpUserRegistry = simpUserRegistry;
}
@GetMapping("/ws/users")
public List<String> connectedEquipments() {
return this.simpUserRegistry
.getUsers()
.stream()
.map(SimpUser::getName)
.collect(Collectors.toList());
}
}