客户端自动重新连接
构建具备韧性的浏览器 WebSocket 客户端,使其能够检测连接中断,并通过指数退避和消息排队自动重新连接。
客户端自动重新连接 是 CoddyKit 上的免费 WebSockets & Realtime Systems Programming 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebSockets & Realtime Systems Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebSockets & Realtime Systems Programming 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Connections Drop
Networks are unreliable. Wi-Fi hiccups, tabs sleep, and servers restart. A good client detects a closed socket and reconnects without the user noticing.
Detecting a Drop
The browser fires close when the connection ends and error on failures. Reconnection logic hooks into close.
ws.addEventListener('close', () => {
scheduleReconnect();
});Naive Reconnect Is Risky
Reconnecting instantly in a tight loop can hammer a struggling server. Instead, wait longer after each failed attempt.
Exponential Backoff
Double the delay each attempt, up to a cap, so a recovering server is not overwhelmed.
let attempt = 0;
function delay() {
return Math.min(1000 * 2 ** attempt, 30000);
}Adding Jitter
If many clients reconnect at once, they create a thundering herd. Random jitter spreads them out.
function delayWithJitter() {
return delay() * (0.5 + Math.random() * 0.5);
}The Reconnect Function
Wrap connection creation so each attempt re-binds handlers and schedules the next retry on failure.
function connect() {
ws = new WebSocket(url);
ws.addEventListener('open', onOpen);
ws.addEventListener('close', scheduleReconnect);
}Resetting on Success
When a connection opens successfully, reset the attempt counter so future drops start backoff fresh.
function onOpen() {
attempt = 0;
flushQueue();
}Queuing Messages While Down
If the user sends while disconnected, buffer the message and send it once reconnected.
const queue = [];
function send(data) {
if (ws.readyState === WebSocket.OPEN) ws.send(data);
else queue.push(data);
}Flushing the Queue
On reconnect, drain the buffer in order.
function flushQueue() {
while (queue.length) ws.send(queue.shift());
}Giving Up Gracefully
After a max number of attempts, surface an error to the user rather than retrying forever.
function scheduleReconnect() {
if (++attempt > 10) return showOffline();
setTimeout(connect, delayWithJitter());
}Best Practices
Build resilient clients:
- Use exponential backoff with jitter
- Reset state on a successful open
- Queue outgoing messages while offline
- Cap retries and inform the user
Quick Check
Test your reconnection knowledge.
Recap
You built an auto-reconnecting client:
- Hook the
closeevent to schedule retries - Use exponential backoff with jitter
- Reset attempts on open
- Queue and flush messages around outages
Your client now survives flaky networks.
常见问题解答
「客户端自动重新连接」课时是免费的吗?
是的 — 「客户端自动重新连接」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Realtime Systems Programming 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Realtime Systems Programming 课程共包含 4 节课。
「客户端自动重新连接」这节课中我会学到什么?
构建具备韧性的浏览器 WebSocket 客户端,使其能够检测连接中断,并通过指数退避和消息排队自动重新连接。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Realtime Systems Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 WebSockets & Realtime Systems Programming 需要有经验吗?
无需任何先前经验。CoddyKit 上的 WebSockets & Realtime Systems Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「客户端自动重新连接」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 WebSockets & Realtime Systems Programming 课中编写并运行代码吗?
能。每节 WebSockets & Realtime Systems Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 浏览器 WebSocket API 基础
- 发送与接收数据
- 客户端事件处理
- 客户端自动重新连接