简体   繁体   中英

capture session id in spring websocket

My WebSocketConfig class is

@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");
    }

}

How can I obtain the WebSocket session id when the connection is established?

When STOMP session is connected, this piece of code is performed:

 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();
            }
        }
    }

Pay attention to the SessionConnectedEvent to be listened with the @EventListener and also to that SimpAttributesContextHolder . You can get access to the sessionId in that event listener using a static API from the SimpAttributesContextHolder .

On the other hand the mentioned message in the event has a particular simpSessionId header for your consideration.

Simple. Just add this method in any class:

@EventListener
    private void handleSessionConnected(SessionConnectEvent event) {
        String sessionId = SimpAttributesContextHolder.currentAttributes().getSessionId();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM