如何处理套接字断开连接和心跳消息?

时间:2019-04-26 12:26:04

标签: java angular spring-boot stomp sockjs

我要做什么

我有一个与玩家一起玩的大厅,当有人离开大厅时,我想为每个客户进行更新,以便显示玩家的实际列表。

我做了什么

为了避免周期性的请求从前端发送到后端,我决定使用web sockets。当有人离开大厅时,请求将发送到REST api,然后后端在接收到此请求后,会执行所有业务逻辑,然后使用套接字“戳”此大厅以更新大厅中的所有客户端。

我的问题

一切正常,除了用户关闭浏览器或选项卡的情况之外,因为在这种情况下我无法发送请求,因此一切正常。 (据我所知,使用javascript和beforeunload事件,onDestroy()方法等是不可能做到的。)

我的问题

是否可以在服务器端检查是否有套接字断开连接,如果可以,我该怎么办?我也尝试使用从前端发送到后端的heartbeat,但是我不知道如何在服务器端处理此heartbeat消息。

服务器端(春季启动)

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguartion implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/api/socket")
                .setAllowedOrigins("*")
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        ThreadPoolTaskScheduler te = new ThreadPoolTaskScheduler();
        te.setPoolSize(1);
        te.setThreadNamePrefix("wss-heartbeat-thread-");
        te.initialize();

        config.enableSimpleBroker("/lobby")
                .setHeartbeatValue(new long[]{0, 1000})
                .setTaskScheduler(te);
    }
}


@Controller
public class WebSocketController {

    private final SimpMessagingTemplate template;

    WebSocketController(SimpMessagingTemplate template) {
        this.template = template;
    }

    public void pokeLobby(@DestinationVariable String lobbyName, SocketMessage message) {
        this.template.convertAndSend("/lobby/"+lobbyName.toLowerCase(), message);
    }
}

客户端

  connectToLobbyWebSocket(lobbyName: string): void {
    const ws = new SockJS(this.addressStorage.apiAddress + '/socket');
    this.stompClient = Stomp.over(ws);
    // this.stompClient.debug = null;
    const that = this;
    this.stompClient.connect({}, function () {
      that.stompClient.subscribe('/lobby/' + lobbyName, (message) => {
        if (message.body) {
          that.socketMessage.next(message.body); // do client logic
        }
      });
    });
  }

1 个答案:

答案 0 :(得分:1)

您可以在应用程序中监听SessionDisconnectEvent,并在收到此类事件时将消息发送给其他客户端。

  

关闭使用简单消息协议(例如STOMP)作为WebSocket子协议的WebSocket客户端的会话时引发的事件。   请注意,对于单个会话,可能会多次引发此事件,因此,事件使用者应该是幂等的,并忽略重复的事件。

还有其他类型的events

相关问题