0Pricing
WebSockets & Realtime Systems Programming · 课时

处理断开连接与重新连接

实现客户端和服务器端逻辑,以检测连接断开并自动尝试重新连接。

处理断开连接与重新连接 是 CoddyKit 上的免费 WebSockets & Realtime Systems Programming 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebSockets & Realtime Systems Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebSockets & Realtime Systems Programming 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Connections Drop

In the real world, network connections aren't always perfect. WebSockets, despite being persistent, can break due to many reasons.

Ignoring these disconnections can lead to unresponsive applications and a poor user experience. This lesson explores how to gracefully handle these interruptions.

Causes of Connection Loss

What makes a WebSocket connection drop?

  • Network Issues: Wi-Fi drops, internet outages, proxy problems.
  • Server Restarts: The server application might restart for updates or maintenance.
  • Client Offline: The user closes their browser, loses power, or puts their device to sleep.
  • Idle Timeouts: Some proxies or firewalls might close idle connections.

Client Detects Disconnects

On the client side, the browser's native WebSocket API provides events to notify you about connection status changes.

The most important event for detecting a disconnection is the onclose event. It fires when the connection is either gracefully closed by the server or abruptly lost.

Simple Reconnect Attempt

When onclose fires, you can immediately try to reconnect. This simple approach works for temporary glitches but can be problematic.

Try running this basic client-side example:

let ws;
function connect() {
  ws = new WebSocket("ws://localhost:8080");

  ws.onopen = () => console.log("Connected!");
  ws.onmessage = (event) => console.log("Received:", event.data);
  ws.onerror = (error) => console.error("WebSocket Error:", error);

  ws.onclose = () => {
    console.log("Disconnected. Reconnecting...");
    setTimeout(connect, 1000); // Try again in 1 second
  };
}
connect();

Why Simple Retries Fail

Continuously trying to reconnect immediately (e.g., every 1 second) can overwhelm both the client and the server.

  • Client Resource Drain: Constant connection attempts consume CPU and network resources.
  • Server Overload: If many clients disconnect and then flood the server with reconnect requests, it can lead to a Denial of Service (DoS) situation.
  • No Backoff: It doesn't account for prolonged outages.

Smart Reconnection: Backoff

To prevent overloading and provide a better experience, we use reconnection backoff strategies.

A backoff strategy introduces delays between reconnection attempts, and these delays typically increase with each failed attempt. This gives the server time to recover and prevents a "thundering herd" problem.

Exponential Backoff Logic

Exponential backoff is a common and effective strategy. It means the delay between retries increases exponentially.

  • First retry: 1 second
  • Second retry: 2 seconds
  • Third retry: 4 seconds
  • Fourth retry: 8 seconds

You usually cap the maximum delay to prevent excessively long waits and add some random "jitter" to avoid synchronized retries.

Client with Exponential Backoff

Let's enhance our client-side code to use exponential backoff with a maximum delay and some random jitter. Try running it!

let ws;
let reconnectInterval = 1000; // Start with 1 second
const maxReconnectInterval = 30000; // Max 30 seconds
let reconnectTimer;

function connect() {
  ws = new WebSocket("ws://localhost:8080");

  ws.onopen = () => {
    console.log("Connected!");
    reconnectInterval = 1000; // Reset on successful connection
    clearTimeout(reconnectTimer);
  };
  ws.onmessage = (event) => console.log("Received:", event.data);
  ws.onerror = (error) => console.error("WebSocket Error:", error);

  ws.onclose = () => {
    console.log(`Disconnected. Retrying in ${reconnectInterval / 1000}s...`);
    reconnectTimer = setTimeout(connect, reconnectInterval);
    reconnectInterval = Math.min(reconnectInterval * 2, maxReconnectInterval);
    // Add some random jitter (e.g., +/- 10%) for better distribution
    reconnectInterval += (Math.random() - 0.5) * reconnectInterval * 0.2;
    reconnectInterval = Math.floor(reconnectInterval);
  };
}
connect();

Server-Side Disconnects

The server also needs to know when a client disconnects. This is crucial for cleaning up resources, updating connected user lists, or stopping data streams for that client.

Using a library like ws in Node.js, the WebSocket server emits a 'close' event on the individual client connection object when it disconnects.

Server Cleanup on Disconnect

Here's a basic Node.js WebSocket server example showing how to handle client disconnections and remove them from an active connections list.

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

let clients = new Set();

wss.on('connection', function connection(ws) {
  clients.add(ws);
  console.log('Client connected. Total:', clients.size);

  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.on('close', function close() {
    clients.delete(ws);
    console.log('Client disconnected. Total:', clients.size);
  });

  ws.send('Welcome!');
});

console.log('WebSocket server started on port 8080');

Check Your Understanding

Consider a client-side WebSocket application that needs to handle disconnections robustly.

Which of the following are good practices for implementing a reconnection strategy?

Recap: Robust Connections

We've explored how crucial it is to handle disconnections in realtime applications. Both client and server play a role in maintaining connection resilience.

  • Clients use onclose to detect disconnections.
  • Exponential backoff with jitter and a max delay prevents server overload during reconnections.
  • Servers use on('close') to clean up resources when clients leave.

These strategies ensure your realtime apps remain responsive and reliable, even in unstable network conditions.

常见问题解答

「处理断开连接与重新连接」课时是免费的吗?

是的 — 「处理断开连接与重新连接」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Realtime Systems Programming 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Realtime Systems Programming 课程共包含 4 节课。

「处理断开连接与重新连接」这节课中我会学到什么?

实现客户端和服务器端逻辑,以检测连接断开并自动尝试重新连接。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Realtime Systems Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebSockets & Realtime Systems Programming 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebSockets & Realtime Systems Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「处理断开连接与重新连接」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 WebSockets & Realtime Systems Programming 课中编写并运行代码吗?

能。每节 WebSockets & Realtime Systems Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 处理断开连接与重新连接
  2. 可靠的错误传播与恢复
  3. 心跳与连接保活
  4. 消息确认与传递保证
← 返回 WebSockets & Realtime Systems Programming