我使用Spring 4、STOMP和sock.js实现了简单的WebSocket通信,遵循以下链接中的步骤:https://github.com/rstoyanchev/spring-websocket-portfolio及http://assets.spring.io/wp/WebSocketBlogPost.html。我想知道在Spring 4.0.0中是否可能捕获连接事件,例如新客户端连接到服务器或客户端断开连接时发生的事件?
Spring WebSocket在从客户端接收消息时发布事件,如果您正在使用STOMP,则会发布以下事件:
最简单的检测连接和断开连接的方法是为上述事件实现一个事件监听器。
@Component
public class WebSocketEventListener {
@EventListener
private void handleSessionConnected(SessionConnectEvent event) {
...
}
@EventListener
private void handleSessionDisconnect(SessionDisconnectEvent event) {
...
}
}
这里是一个跟踪已连接用户的示例实现:https://github.com/salmar/spring-websocket-chat/blob/master/src/main/java/com/sergialmar/wschat/event/PresenceEventListener.java
可以通过连接握手拦截器 (HttpSessionHandshakeInterceptor) 完成,引用文档:
自定义初始HTTP WebSocket握手请求的最简单方法是使用HandshakeInterceptor,它公开了“before”和“after”握手方法。
我了解到,这个问题与DISCONNECT事件有关,在这个话题中没有得到解决。握手拦截只提供连接信息而不提供断开连接的信息。
我已经通过入站通道的拦截器来实现这一点:
<websocket:message-broker>
...
<websocket:client-inbound-channel>
<websocket:interceptors>
<bean class="com......MyChannelInterception"></bean>
</websocket:interceptors>
</websocket:client-inbound-channel>
</websocket:message-broker>
...and class...
import java.security.Principal;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.ChannelInterceptorAdapter;
public class MyChannelInterception extends ChannelInterceptorAdapter {
private static final Logger LOGGER = LogManager.getLogger(WrcChannelInterception.class);
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
MessageHeaders headers = message.getHeaders();
SimpMessageType type = (SimpMessageType) headers.get("simpMessageType");
String simpSessionId = (String) headers.get("simpSessionId");
if (type == SimpMessageType.CONNECT) {
Principal principal = (Principal) headers.get("simpUser");
LOGGER.debug("WsSession " + simpSessionId + " is connected for user " + principal.getName());
} else if (type == SimpMessageType.DISCONNECT) {
LOGGER.debug("WsSession " + simpSessionId + " is disconnected");
}
return message;
}
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
logger.info("afterConnectionEstablished called");
}
虽然原问题是关于Spring 4的 - Sergi已经很好地回答了。这里介绍一种在Spring 5或Spring Boot 2中实现它的方法(Spring Boot 2在内部使用Spring 5)。需要实现ApplicationListener:
@Component
public class WebSocketEventListener implements ApplicationListener<SessionConnectEvent> {
Logger logger = LoggerFactory.getLogger(WebSocketEventListener.class);
@Override
public void onApplicationEvent(SessionConnectEvent event) {
logger.error("SessionConnectEvent = " + event);
}
}