Video in progress

What are ping and pong frames in WebSocket for?

Ping/pong are control frames that check the connection is still alive. One side sends a ping, and the other must answer with a pong. This both detects dead connections and stops proxies from closing the connection on their idle timeout.

📖 Answer

The connection is open, but no message has moved for 5 minutes. Two things can be going on:

  • the Nginx or cloud load balancer in the middle decides "this connection isn't being used" and quietly closes it (often after 60 seconds);
  • the client's phone dropped off the network, but the server doesn't know and still considers the connection open.

Sending a ping every so often solves both: there is traffic, so the proxy doesn't close the connection, and if no pong comes back, the connection is treated as dead and closed.

The browser answers pings automatically, but JavaScript has no API to send a ping. That's why many apps do heartbeats at the application level, for example a STOMP heartbeat or a {"type":"ping"} JSON message.

Sending a ping through a raw handler in Spring:

session.sendMessage(new PingMessage());