我的WebSocketConfig
类是
@EnableWebSocket
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker( MessageBrokerRegistry registry )
{
registry.enableSimpleBroker("/topic", "/queue");
registry.setApplicationDestinationPrefixes("/user");
registry.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints( StompEndpointRegistry stompEndpointRegistry )
{
stompEndpointRegistry.addEndpoint("/ws").withSockJS();
stompEndpointRegistry.addEndpoint("/ws");
}
}
建立连接后,如何获取WebSocket会话ID?
答案 0 :(得分:0)
连接STOMP会话后,将执行以下代码:
else if (StompCommand.CONNECTED.equals(command)) {
this.stats.incrementConnectedCount();
accessor = afterStompSessionConnected(message, accessor, session);
if (this.eventPublisher != null && StompCommand.CONNECTED.equals(command)) {
try {
SimpAttributes simpAttributes = new SimpAttributes(session.getId(), session.getAttributes());
SimpAttributesContextHolder.setAttributes(simpAttributes);
Principal user = getUser(session);
publishEvent(this.eventPublisher, new SessionConnectedEvent(this, (Message<byte[]>) message, user));
}
finally {
SimpAttributesContextHolder.resetAttributes();
}
}
}
请注意要与SessionConnectedEvent
一起收听的@EventListener
以及该SimpAttributesContextHolder
。您可以使用sessionId
中的静态API访问该事件监听器中的SimpAttributesContextHolder
。
另一方面,事件中提到的消息具有特定的simpSessionId
标头供您考虑。
答案 1 :(得分:0)
简单。只需在任何类中添加此方法:
@EventListener
private void handleSessionConnected(SessionConnectEvent event) {
String sessionId = SimpAttributesContextHolder.currentAttributes().getSessionId();
}