WebSocket 완전 정복 · 1부. 기초 · 16편 중 5편
이전 편: 4편 — 브라우저 API
브라우저 쪽을 봤으니 이제 상대편을 세웁니다. Node.js의 ws 라이브러리로 연결을 받아 모든 클라이언트에 되돌려 주는 브로드캐스트 서버를 만들고, 터미널 두 개로 확인합니다.
ws로 만드는 브로드캐스트 서버
ts
// server.ts
import { WebSocketServer, WebSocket } from "ws";
const wss = new WebSocketServer({ port: 8080, maxPayload: 64 * 1024 });
wss.on("connection", (ws, req) => {
console.log("connected from", req.socket.remoteAddress);
ws.on("message", (data, isBinary) => {
// 모든 클라이언트에게 브로드캐스트
for (const client of wss.clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(data, { binary: isBinary });
}
}
});
ws.on("close", (code, reason) => {
console.log("closed", code, reason.toString());
});
});터미널 두 개로 확인하기
wscat -c ws://localhost:8080으로 터미널 두 개를 열어 테스트합니다. maxPayload 기본값은 100MiB로 매우 크므로 처음부터 줄여 두세요.
더 깊이
- 4편 — 브라우저 API: readyState, bufferedAmount, onclose가 알려주는 것: 이 서버에 붙는 클라이언트 쪽 코드입니다. 위 서버의
client.readyState === WebSocket.OPEN검사가 브라우저의readyState와 같은 값을 보는 것임을 함께 확인해 보세요.