我希望能够检测到用户何时失去与服务器的连接(关闭标签,丢失的互联网连接等)。我在客户端上使用Sockjs上的stompjs并在我的服务器上使用spring mvc websockets。
如何检测客户端何时断开连接。 这是我如何配置我的websocket消息brocket:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {
@Autowired
private TaskScheduler scheduler;
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic").setHeartbeatValue(new long[]{10000, 10000}).setTaskScheduler(scheduler);
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/web").setAllowedOrigins("*").withSockJS();
}
}
这是我的控制器类,它实际处理传入的套接字消息:
@RestController
@CrossOrigin
public class WebMessagingController {
@MessageMapping("/chat/message")
public void newUserMessage(String json) throws IOException {
messagesProcessor.processUserMessage(json);
}
}
我知道如果我会使用从 TextWebSocketHandler 扩展的类,我会让bean能够覆盖在连接和断开客户端时调用的方法,但我不认为这将与sock-js客户端一起使用。 谢谢。
答案 0 :(得分:1)
从class ProductController extends Controller
{
protected $indexManager;
public function __construct(IndexManagerInterface $indexingManager)
{
$this->indexManager = $indexingManager;
}
public function displayAction(Request $request) {
$em = $this->getDoctrine()->getManagerForClass(Product::class);
$posts = $this->indexManager->search('query', Product::class, $em);
return $this->render('ProductBundle:Default:postDisplay.html.twig', array(
'posts' => $posts));
}
}
调用的StompSubProtocolHandler
实现afterSessionEnded()
。前者发布了这样的事件:
WebSocketHandler.afterConnectionClosed()
因此,您需要的是此/**
* Event raised when the session of a WebSocket client using a Simple Messaging
* Protocol (e.g. STOMP) as the WebSocket sub-protocol is closed.
*
* <p>Note that this event may be raised more than once for a single session and
* therefore event consumers should be idempotent and ignore a duplicate event.
*
* @author Rossen Stoyanchev
* @since 4.0.3
*/
@SuppressWarnings("serial")
public class SessionDisconnectEvent extends AbstractSubProtocolEvent {
的{{1}},并且事件中包含所有信息。
答案 1 :(得分:0)
除了Artem的回复,你可以在任何 spring bean 中使用@EventListener注释:
@EventListener
public void onDisconnectEvent(SessionDisconnectEvent event) {
LOGGER.debug("Client with username {} disconnected", event.getUser());
}