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

Heartbeat i mechanizmy podtrzymywania ping/pong

Wcześnie wykryją Państwo martwe połączenia WebSocket za pomocą ramek ping/pong i heartbeat STOMP, aby serwer odzyskiwał zasoby, a klienci szybko nawiązywali połączenie ponownie.

Heartbeat i mechanizmy podtrzymywania ping/pong to bezpłatna lekcja WebSockets & Real-Time Systems with Spring na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej WebSockets & Real-Time Systems with Spring, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs WebSockets & Real-Time Systems with Spring zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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

Często zadawane pytania

Czy lekcja „Heartbeat i mechanizmy podtrzymywania ping/pong” jest bezpłatna?

Tak — pełny tekst „Heartbeat i mechanizmy podtrzymywania ping/pong” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu WebSockets & Real-Time Systems with Spring, przejdź na CoddyKit PRO. Kurs WebSockets & Real-Time Systems with Spring zawiera 4 lekcji w sumie.

Co nauczysz się w „Heartbeat i mechanizmy podtrzymywania ping/pong”?

Wcześnie wykryją Państwo martwe połączenia WebSocket za pomocą ramek ping/pong i heartbeat STOMP, aby serwer odzyskiwał zasoby, a klienci szybko nawiązywali połączenie ponownie. Ćwiczysz WebSockets & Real-Time Systems with Spring z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć WebSockets & Real-Time Systems with Spring?

Nie wymagamy żadnego doświadczenia. WebSockets & Real-Time Systems with Spring w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Heartbeat i mechanizmy podtrzymywania ping/pong”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji WebSockets & Real-Time Systems with Spring?

Tak. Każda lekcja WebSockets & Real-Time Systems with Spring zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Elegancka obsługa błędów WebSocket
  2. Zarządzanie cyklem życia połączenia
  3. Ponawianie prób i mechanizmy awaryjne
  4. Heartbeat i mechanizmy podtrzymywania ping/pong
← Powrót do WebSockets & Real-Time Systems with Spring