Understanding: Ping & Heartbeat
Learn how real-time applications maintain connection health and measure network latency using ping/pong mechanisms.
What is Ping?
Connection Health Check
Ping is a simple message sent from a client to a server to check if the connection is still alive and to measure the round-trip time (latency) of the network.
In real-time games like Fly & Fight, ping messages are crucial for:
- Connection verification - Ensuring the WebSocket connection is still active
- Latency measurement - Calculating how long it takes for data to travel to the server and back
- Dead connection detection - Identifying when a client has disconnected without closing the socket properly
// Client sends:
{ "type": "ping" }
// Server responds:
{ "type": "pong" }
What is Heartbeat?
Automatic Connection Monitoring
Heartbeat is an automated, periodic ping mechanism that runs continuously in the background to maintain connection health.
While a ping is a single request-response pair, a heartbeat is a system that sends pings at regular intervals (e.g., every 5-30 seconds).
Single Ping
- Manual or on-demand
- One-time check
- User-triggered
Heartbeat
- Automatic & periodic
- Continuous monitoring
- Background process
Why It Matters
Real-Time Game Requirements
Player Experience
High latency means delayed responses. In a fast-paced game, even 100ms delay can make controls feel unresponsive.
Server Resources
Detecting dead connections quickly allows the server to free resources and remove ghost players from the game.
Game Fairness
Knowing each player's latency helps the server make fair decisions about hit detection and game events.
Try It Yourself
Interactive Demo
Interactive Ping Demo
Click "Connect" to establish a WebSocket connection...
Server: wss://io00c800s8cw8c0cc0o0ck0s.apps.pb.games/ws
Implementation
Code Example
Basic Heartbeat Implementation
// Client-side heartbeat
const HEARTBEAT_INTERVAL = 10000; // 10 seconds
function startHeartbeat(ws: WebSocket) {
const intervalId = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: "ping" }));
}
}, HEARTBEAT_INTERVAL);
// Clean up on disconnect
ws.onclose = () => clearInterval(intervalId);
}
// Listen for pong responses
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === "pong") {
console.log("Connection healthy");
}
};Latency Reference
What the Numbers Mean
| Latency | Experience | Suitable For |
|---|---|---|
| < 50ms | Excellent | Fast-paced shooters, fighting games |
| 50-100ms | Good | Most multiplayer games, Fly & Fight |
| 100-200ms | Acceptable | Turn-based games, casual multiplayer |
| > 200ms | Poor | Noticeable lag, may affect gameplay |