0Pricing
WebSockets & Real-Time Systems with Spring · Lezione

Heartbeat e keep-alive Ping/Pong

Rilevi tempestivamente le connessioni WebSocket interrotte usando frame ping/pong e heartbeat STOMP, così il server recupera le risorse e i client si riconnettono rapidamente.

Heartbeat e keep-alive Ping/Pong è una lezione WebSockets & Real-Time Systems with Spring gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento WebSockets & Real-Time Systems with Spring, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso WebSockets & Real-Time Systems with Spring include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

The Silent Death Problem

A WebSocket can look open long after the peer has vanished. A laptop lid closes, a network drops, a NAT mapping expires — yet neither side gets a close frame. This is a half-open connection.

Why It Matters

Half-open sockets waste server memory, keep sessions in maps forever, and let the client believe it is still receiving updates. You need an active probe to discover the truth: a heartbeat.

Ping/Pong Control Frames

The WebSocket protocol defines ping and pong control frames. One side sends a ping; a healthy peer must reply with a pong. No pong within a deadline means the connection is dead.

STOMP Heartbeats in Spring

When you use STOMP over WebSocket, Spring exposes heartbeat configuration. The two numbers are the rate (ms) the server sends and the rate it expects to receive heartbeats.

registry.enableSimpleBroker("/topic")
  .setHeartbeatValue(new long[]{10000, 10000})
  .setTaskScheduler(heartbeatScheduler());

A Scheduler Is Required

Heartbeats need a TaskScheduler to fire on time. Without one Spring silently disables them.

@Bean
public ThreadPoolTaskScheduler heartbeatScheduler() {
  ThreadPoolTaskScheduler s = new ThreadPoolTaskScheduler();
  s.setPoolSize(1);
  s.initialize();
  return s;
}

Client-Side STOMP Heartbeats

The client declares the matching heartbeat interval. Negotiation picks the slower of each side's value.

const client = new StompJs.Client({
  brokerURL: 'wss://api.example.com/ws',
  heartbeatIncoming: 10000,
  heartbeatOutgoing: 10000
});

Raw Ping at the Container Level

For plain (non-STOMP) handlers you can send ping frames directly from the server session.

PingMessage ping = new PingMessage(ByteBuffer.wrap(new byte[]{1}));
session.sendMessage(ping);

Choosing an Interval

Tune the interval to your needs:

  • Too short wastes bandwidth and battery on mobile
  • Too long delays detection of dead peers
  • 10–30 seconds is a common sweet spot

Beating Idle Timeouts

Proxies and load balancers drop connections that are idle too long (often 60s). A heartbeat doubles as keep-alive traffic that resets those idle timers and stops them from killing a healthy socket.

Reacting to a Missed Beat

When a heartbeat is missed, Spring closes the session and fires afterConnectionClosed. Use that hook to clean up state and let the client trigger its reconnect logic.

@Override
public void afterConnectionClosed(WebSocketSession s, CloseStatus status) {
  registry.remove(s.getId());
  log.warn("Closed {} - {}", s.getId(), status);
}

Heartbeats vs Application Acks

A heartbeat proves the transport is alive; it does not prove your message was processed. For business-level guarantees you still need application acknowledgements on top of heartbeats.

Quick Check

Test your grasp of keep-alives.

Recap

You made connections self-healing:

  • Half-open sockets die silently; heartbeats expose them
  • Ping/pong control frames probe transport health
  • STOMP heartbeats need a TaskScheduler and matching client intervals
  • Heartbeats also defeat proxy idle timeouts
  • Use the close callback to clean up and trigger reconnects

Domande Frequenti

La lezione «Heartbeat e keep-alive Ping/Pong» è gratuita?

Sì — il testo completo di «Heartbeat e keep-alive Ping/Pong» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso WebSockets & Real-Time Systems with Spring, passa a CoddyKit PRO. Il corso WebSockets & Real-Time Systems with Spring include 4 lezioni in totale.

Cosa imparerò in «Heartbeat e keep-alive Ping/Pong»?

Rilevi tempestivamente le connessioni WebSocket interrotte usando frame ping/pong e heartbeat STOMP, così il server recupera le risorse e i client si riconnettono rapidamente. Eserciti WebSockets & Real-Time Systems with Spring con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare WebSockets & Real-Time Systems with Spring?

Non è richiesta alcuna esperienza precedente. WebSockets & Real-Time Systems with Spring su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Heartbeat e keep-alive Ping/Pong»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione WebSockets & Real-Time Systems with Spring?

Sì. Ogni lezione WebSockets & Real-Time Systems with Spring include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Gestione corretta degli errori WebSocket
  2. Gestione del ciclo di vita delle connessioni
  3. Tentativi e fallback
  4. Heartbeat e keep-alive Ping/Pong
← Torna a WebSockets & Real-Time Systems with Spring