心跳与 Ping/Pong 保活
使用 Ping/Pong 帧和 STOMP 心跳及时检测失效的 WebSocket 连接,让服务器回收资源,并让客户端及时重新连接。
心跳与 Ping/Pong 保活 是 CoddyKit 上的免费 WebSockets & Real-Time Systems with Spring 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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
TaskSchedulerand matching client intervals - Heartbeats also defeat proxy idle timeouts
- Use the close callback to clean up and trigger reconnects
常见问题解答
「心跳与 Ping/Pong 保活」课时是免费的吗?
是的 — 「心跳与 Ping/Pong 保活」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 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,全天候 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 反馈 — 无需本地设置。
此课程中的所有课时
- 优雅处理 WebSocket 错误
- 连接生命周期管理
- 重试与回退
- 心跳与 Ping/Pong 保活