구성 요소 | 설명 |
---|---|
React | 클라이언트(UI) 역할 |
Node.js + ws | WebSocket 서버 (실시간 처리 담당) |
모노레포 | client/ (React), server/ (Node.js) 구조로 프로젝트 구성 |
import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ port: 8081 });
wss.on("connection", (ws) => {
ws.on("message", (message) => {
// 모든 클라이언트에게 메시지 전송 (브로드캐스트)
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message.toString());
}
});
});
});
✅ 역할: 메시지를 받은 후 → 모든 클라이언트에게 다시 전송 (broadcast)
useEffect(() => {
socketRef.current = new WebSocket("ws://localhost:8081");
socketRef.current.onmessage = (event) => {
setMessages((prev) => [...prev, event.data]);
};
return () => socketRef.current?.close();
}, []);
✅ WebSocket 연결은 마운트 시 한 번만
✅ .onmessage
는 서버로부터 메시지 받을 때마다 호출
const handleSend = () => {
const fullMessage = `${username}: ${input}`;
socketRef.current.send(fullMessage);
};
✅ "영목: 안녕하세요"
형식으로 서버에 메시지 전송
✅ 서버는 받은 메시지를 모든 클라이언트에게 전달