WebSocket
WebSocket
A two-way real-time communication protocol. Chat, gaming, real-time notifications.
WebSocket
A two-way real-time communication protocol. Chat, gaming, real-time notifications.
WebSocket is a protocol for bidirectional real-time communication between a client and a server. Unlike HTTP, once a connection is established it is kept open, so the server can push data to the client at any time. It is essential for chat, real-time notifications, games, stock quotes, and more.
WebSocket starts with an HTTP handshake. When the client sends an Upgrade: websocket header, the server responds with 101 Switching Protocols and the protocol is switched. After that, bidirectional messages are exchanged over the ws:// or wss:// (secure) protocol.
Compared with HTTP polling, the advantages of WebSocket are latency and network efficiency. Unlike HTTP, which opens and closes a connection every time, the connection is kept open, so there is no header overhead and the server can send messages immediately. However, because state must be maintained, horizontal scaling is complex.
In practice, Socket.IO (Node.js), ws (a pure Node.js implementation), Spring WebSocket (Java), and others are used. Socket.IO provides convenience features such as automatic reconnection, rooms/namespaces, and polling fallback. Managed WebSocket is also supported by AWS API Gateway, Cloudflare, and others.
// 브라우저 WebSocket API - 기본 사용법
const ws = new WebSocket('wss://example.com/chat');
// 연결 성공
ws.onopen = () => {
console.log('WebSocket 연결됨');
ws.send(JSON.stringify({ type: 'join', room: 'general' }));
};
// 메시지 수신
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('메시지 수신:', data);
};
// 연결 종료
ws.onclose = (event) => {
console.log(`연결 종료: ${event.code} ${event.reason}`);
};
// 에러 처리
ws.onerror = (error) => {
console.error('WebSocket 에러:', error);
};
// 메시지 전송
ws.send(JSON.stringify({ type: 'message', text: '안녕하세요!' }));
// 재연결 로직 (지수 백오프)
function connectWithRetry(url, maxRetries = 5) {
let retries = 0;
function connect() {
const ws = new WebSocket(url);
ws.onclose = () => {
if (retries < maxRetries) {
const delay = Math.pow(2, retries) * 1000; // 1s, 2s, 4s, 8s...
console.log(`${delay/1000}초 후 재연결 시도...`);
setTimeout(connect, delay);
retries++;
}
};
ws.onopen = () => { retries = 0; }; // 성공시 리셋
return ws;
}
return connect();
}
// Node.js 서버 (ws 라이브러리)
import { WebSocketServer, WebSocket } from 'ws';
import http from 'http';
// HTTP 서버와 함께 WebSocket 서버 생성
const server = http.createServer();
const wss = new WebSocketServer({ server });
// 연결된 클라이언트 관리
const clients = new Map();
wss.on('connection', (ws, req) => {
const clientId = req.headers['sec-websocket-key'];
clients.set(clientId, ws);
console.log(`클라이언트 연결: ${clientId}`);
// ping/pong으로 연결 상태 확인
ws.isAlive = true;
ws.on('pong', () => { ws.isAlive = true; });
// 메시지 수신
ws.on('message', (data) => {
const message = JSON.parse(data);
console.log('수신:', message);
// 모든 클라이언트에게 브로드캐스트
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
...message,
timestamp: Date.now()
}));
}
});
});
ws.on('close', () => {
clients.delete(clientId);
console.log(`클라이언트 종료: ${clientId}`);
});
});
// Heartbeat - 30초마다 연결 상태 확인
const heartbeat = setInterval(() => {
wss.clients.forEach((ws) => {
if (!ws.isAlive) return ws.terminate();
ws.isAlive = false;
ws.ping();
});
}, 30000);
wss.on('close', () => clearInterval(heartbeat));
server.listen(8080, () => console.log('WebSocket 서버: ws://localhost:8080'));
// Socket.IO (룸, 네임스페이스, 자동 재연결)
import { Server } from 'socket.io';
const io = new Server(server, { cors: { origin: '*' } });
io.on('connection', (socket) => {
socket.join('room-1'); // 룸 참가
socket.to('room-1').emit('user-joined', socket.id); // 룸에 브로드캐스트
});
# Python 클라이언트 (websockets 라이브러리)
import asyncio
import websockets
import json
# 기본 WebSocket 클라이언트
async def websocket_client():
uri = "wss://example.com/chat"
async with websockets.connect(uri) as ws:
# 메시지 전송
await ws.send(json.dumps({
"type": "join",
"room": "general"
}))
# 메시지 수신 (무한 루프)
async for message in ws:
data = json.loads(message)
print(f"수신: {data}")
asyncio.run(websocket_client())
# Python 서버 (websockets 라이브러리)
import asyncio
import websockets
import json
connected_clients = set()
async def handler(websocket, path):
connected_clients.add(websocket)
try:
async for message in websocket:
data = json.loads(message)
print(f"수신: {data}")
# 모든 클라이언트에게 브로드캐스트
broadcast = json.dumps({**data, "timestamp": asyncio.get_event_loop().time()})
await asyncio.gather(
*[client.send(broadcast) for client in connected_clients]
)
finally:
connected_clients.remove(websocket)
async def main():
async with websockets.serve(handler, "localhost", 8080):
print("WebSocket 서버: ws://localhost:8080")
await asyncio.Future() # 무한 대기
asyncio.run(main())
# FastAPI + WebSocket (프로덕션 권장)
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from typing import List
app = FastAPI()
connections: List[WebSocket] = []
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
connections.append(websocket)
try:
while True:
data = await websocket.receive_json()
for conn in connections:
await conn.send_json(data)
except WebSocketDisconnect:
connections.remove(websocket)
"For real-time chat, WebSocket is the right choice. Polling has latency and puts a heavy load on the server. Socket.IO is convenient because it has automatic reconnection and room features. If there are multiple servers, you can broadcast messages with the Redis Adapter."
"WebSocket performs bidirectional full-duplex communication after an HTTP handshake. Unlike HTTP/2 Server Push, the client can also send messages to the server at any time. Because keeping connections open has a cost, connection count management and horizontal scaling strategy are important in large-scale services."
"If the WebSocket connection drops often, check the timeout settings of the proxy or load balancer. You need to keep the connection alive with ping/pong frames and implement reconnection logic on the client. Socket.IO has this built in by default."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
The connection can drop because of an unstable network, a server restart, a proxy timeout, and so on. Implement automatic reconnection with exponential backoff (1 second, 2 seconds, 4 seconds...) or use a library with it built in, such as Socket.IO.
Proxies, load balancers, and firewalls close idle connections. You need to exchange ping/pong frames every 30 seconds to keep the connection alive and check its status. With Nginx, also check the proxy_read_timeout setting.
When you run WebSocket on multiple servers, a connection is tied to a specific server. You need to share messages between servers using Redis Pub/Sub (Socket.IO Adapter), Kafka, AWS API Gateway + Lambda, and so on.
Implement JWT token authentication at connection time, a 30-second heartbeat, duplicate prevention with message IDs, and monitoring of connection count and memory. If you only need one-way notifications, Server-Sent Events (SSE) are simpler.