我正在使用Spring编写简单的Stomp Websocket应用程序,客户端既包括Web(Javascript),也包括移动端(iOS、Android)。从JS代码客户端通过SockJS连接,而移动客户端则使用SockJS后面的普通websocket连接。
问题在于,在我的
Websocket starter参考了这里的Spring示例:https://github.com/spring-guides/gs-messaging-stomp-websocket.git Websocket配置:
当我在JS应用程序中通过SockJS连接时(http://localhost:8080/gs-guide-websocket - 并让Spring SockJS处理剩下的部分):
问题在于,在我的
ChannelInterceptor
中检查身份验证的行为对于不同类型的连接是完全不同的。我无法使其对每个客户端都起作用。让我简要介绍一下代码,并通过示例进行解释:Websocket starter参考了这里的Spring示例:https://github.com/spring-guides/gs-messaging-stomp-websocket.git Websocket配置:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gs-guide-websocket")
.setAllowedOrigins("*")
.withSockJS();
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(new MyChannelInterceptor());
}
}
还有ChannelInterceptor
本身:
public class MyChannelInterceptor implements ChannelInterceptor {
@Override
public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
StompCommand command = accessor.getCommand();
...
}
}
当我在JS应用程序中通过SockJS连接时(http://localhost:8080/gs-guide-websocket - 并让Spring SockJS处理剩下的部分):
- 我可以在
MyChannelInterceptor
的postSend
方法中捕获CONNECT
命令- OK - 当我关闭连接时,在同一位置,
DISCONNECT
命令会触发两次。- 不OK
- 我无法在
MyChannelInterceptor
的postSend
方法中捕获CONNECT
命令- 严重 - 当我关闭连接时,
DISCONNECT
命令会正确触发一次。- OK
- 我已经尝试在配置中删除
.withSockJs()
并仅连接到套接字-相同的问题 - 我还尝试在
SessionConnectEvent
和SessionConnectedEvent
上实现应用程序事件监听器-相同的问题