WebSocket heartbeat stops sending PING and then receives "Connection closed"

205 Views Asked by At

I have a Spring Boot WebSocket application that uses StompJS. There is a heartbeat setup for every 10 seconds to keep the connection alive. Periodically (maybe 2-10 minutes) the connection will be closed. The debug output from StompJS seems to indicate that PING requests stop getting sent, which makes me wonder if that's causing the client to think that the connection is stale and reconnects.

This is the implementation of Spring's WebSocketMessageBrokerConfigurer.java, setting the heartbeat to 10 seconds.

public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker("/topic")
            .setHeartbeatValue(new long[]{ 10000, 10000 })
            .setTaskScheduler(new DefaultManagedTaskScheduler());
    registry.setApplicationDestinationPrefixes("/app");
}

And this is the StompJS client setup in JavaScript, setting heartbeat to 10 seconds:

const stompClient = new StompJs.Client({
    heartbeatIncoming: 10000,
    heartbeatOutgoing: 10000
});

Below is the output from StompJS's debug() method. Note that the PING is sent every 10 seconds until the final one at 12:55:43. The connection is closed 39 seconds later. The PONG message continues throughout this period.

12:55:22 :: Received data
12:55:22 :: <<< PONG
12:55:23 :: >>> PING
12:55:32 :: Received data
12:55:32 :: <<< PONG
12:55:33 :: >>> PING
12:55:42 :: Received data
12:55:42 :: <<< PONG
12:55:43 :: >>> PING
12:55:52 :: Received data
12:55:52 :: <<< PONG
12:56:02 :: Received data
12:56:02 :: <<< PONG
12:56:12 :: Received data
12:56:12 :: <<< PONG
12:56:22 :: Received data
12:56:22 :: <<< PONG
12:56:22 :: Connection closed to wss://example.com/ws
12:56:22 :: STOMP: scheduling reconnection in 300ms
12:56:22 :: Opening Web Socket...
12:56:22 :: Web Socket Opened...
12:56:22 :: >>> CONNECT

Does the stop in PING messages cause the WebSocket connection to disconnect? If so, is there a way to ensure that PING messages continue going out?  

This is related to another question I posted here that I might need to delete as it could be irrelevant based on this question.

1

There are 1 best solutions below

0
On

This turns out to be an issue with a browser tab going inactive, and the browser does not maintain the heartbeat (which the browser understandable considers expected behavior).

Client stops sending heart beat outgoing packets · Issue #248 · stomp-js/ng2-stompjs (github.com)

[Documentation improvements] HeartBeats stops working when the tabs goes inactive on Chrome 88+ · Issue #335 · stomp-js/stompjs (github.com)

My workaround will be to manually send a heartbeat from the server to the client, to keep the connection open.