在spring websocket中捕获会话ID

问题描述 投票:0回答:1

我的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?

java spring spring-boot websocket spring-websocket
1个回答
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@EventListenerSimpAttributesContextHolder听。您可以使用sessionId中的静态API访问该事件监听器中的SimpAttributesContextHolder

另一方面,事件中提到的消息有一个特定的simpSessionId标题供您考虑。

© www.soinside.com 2019 - 2024. All rights reserved.