연결 끊김과 재연결 처리
연결 끊김을 감지하고 자동으로 재연결을 시도하는 클라이언트 측 및 서버 측 로직을 구현합니다.
연결 끊김과 재연결 처리은(는) CoddyKit의 무료 WebSockets & Realtime Systems Programming 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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
oncloseto 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.
자주 묻는 질문
“연결 끊김과 재연결 처리” 강의는 무료인가요?
네 — “연결 끊김과 재연결 처리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Realtime Systems Programming 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“연결 끊김과 재연결 처리”에서 뭘 배우나요?
연결 끊김을 감지하고 자동으로 재연결을 시도하는 클라이언트 측 및 서버 측 로직을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Realtime Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
WebSockets & Realtime Systems Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Realtime Systems Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“연결 끊김과 재연결 처리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 WebSockets & Realtime Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 WebSockets & Realtime Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 연결 끊김과 재연결 처리
- 견고한 오류 전파와 복구
- 하트비트와 연결 유지
- 메시지 승인과 전달 보장