クライアントでの自動再接続
切断を検知し、指数バックオフとメッセージキューを使って自動再接続する、堅牢なブラウザーWebSocketクライアントを構築します。
「クライアントでの自動再接続」はCoddyKit上の無料WebSockets & Realtime Systems Programmingレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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.
よくある質問
「クライアントでの自動再接続」レッスンは無料ですか?
はい。「クライアントでの自動再接続」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、WebSockets & Realtime Systems Programmingコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 WebSockets & Realtime Systems Programmingコースには全4レッスンが含まれています。
「クライアントでの自動再接続」で何を学びますか?
切断を検知し、指数バックオフとメッセージキューを使って自動再接続する、堅牢なブラウザーWebSocketクライアントを構築します。 ブラウザで直接実行するハンズオンコードでWebSockets & Realtime Systems Programmingを演習し、24時間対応の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の基礎
- データの送受信
- クライアント側のイベント処理
- クライアントでの自動再接続