0Pricing
WebSockets & Real-Time Systems with Spring · レッスン

ハートビートとPing/Pongキープアライブ

Ping/PongフレームとSTOMPハートビートを使って停止したWebSocket接続を早期に検出し、サーバーがリソースを解放してクライアントが速やかに再接続できるようにする方法を学びます。

「ハートビートとPing/Pongキープアライブ」はCoddyKit上の無料WebSockets & Real-Time Systems with Springレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはWebSockets & Real-Time Systems with Spring学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 WebSockets & Real-Time Systems with Springコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

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

よくある質問

「ハートビートとPing/Pongキープアライブ」レッスンは無料ですか?

はい。「ハートビートとPing/Pongキープアライブ」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、WebSockets & Real-Time Systems with Springコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 WebSockets & Real-Time Systems with Springコースには全4レッスンが含まれています。

「ハートビートとPing/Pongキープアライブ」で何を学びますか?

Ping/PongフレームとSTOMPハートビートを使って停止したWebSocket接続を早期に検出し、サーバーがリソースを解放してクライアントが速やかに再接続できるようにする方法を学びます。 ブラウザで直接実行するハンズオンコードでWebSockets & Real-Time Systems with Springを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

WebSockets & Real-Time Systems with Springを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのWebSockets & Real-Time Systems with Springは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「ハートビートとPing/Pongキープアライブ」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このWebSockets & Real-Time Systems with Springレッスンでコードを書いて実行できますか?

はい。すべてのWebSockets & Real-Time Systems with Springレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. WebSocketエラーの適切な処理
  2. 接続ライフサイクルの管理
  3. 再試行とフォールバック
  4. ハートビートとPing/Pongキープアライブ
← WebSockets & Real-Time Systems with Springに戻る