WebSocket 기본 [하단 링크 참고]
https://velog.io/@fasongsong/WebSocket-%EC%9D%B4%EB%9E%80
project-root
│
├── front
│ └── index.html
└── index.js
브로드캐스팅 기능 구현: 모든 클라이언트에게 메시지를 전송하는 기능을 추가.
서버 접속 및 연결 해제 정보 전송: 클라이언트 접속 및 연결 해제 시 모든 클라이언트에게 정보를 전송.
사용자 이름과 메시지 전송: 클라이언트가 사용자 이름과 메시지를 전송하고, 이를 모든 클라이언트에게 전달.
서버 코드 (index.js)
클라이언트 코드 (index.html)
const express = require("express");
const { WebSocketServer } = require("ws");
const app = express();
app.use(express.static("front"));
app.listen(8000, () => {
console.log(`Server listening on port 8000`);
});
const wss = new WebSocketServer({ port: 8001 });
const clients = new Set();
wss.on("connection", ws => {
clients.add(ws);
console.log("New client connected");
// Notify all clients about the new connection
const connectMsg = `새로운 유저 접속 [현재 : ${clients.size}명]`;
for (let client of clients) {
if (client.readyState === ws.OPEN) {
client.send(JSON.stringify({
type: "notification",
msg: connectMsg
}));
}
}
ws.on("message", data => {
const message = JSON.parse(data);
console.log(`Received from client: ${message.name}: ${message.msg}`);
// Broadcast the message to all clients
for (let client of clients) {
if (client.readyState === ws.OPEN) {
client.send(JSON.stringify({
type: "message",
name: message.name,
msg: message.msg
}));
}
}
});
ws.on("close", () => {
clients.delete(ws);
console.log("Client disconnected");
// Notify all clients about the disconnection
const disconnectMsg = `유저 연결 해제 [현재 : ${clients.size}명]`;
for (let client of clients) {
if (client.readyState === ws.OPEN) {
client.send(JSON.stringify({
type: "notification",
msg: disconnectMsg
}));
}
}
});
const express = require("express");
const { WebSocketServer } = require("ws");
const app = express();
app.use(express.static("front"));
app.listen(8000, () => {
console.log(`Server listening on port 8000`);
});
const wss = new WebSocketServer({ port: 8001 });
const clients = new Set();
wss.on("connection", ws => {
clients.add(ws);
console.log("New client connected");
// Notify all clients about the new connection
const connectMsg = `새로운 유저 접속 [현재 : ${clients.size}명]`;
for (let client of clients) {
if (client.readyState === ws.OPEN) {
client.send(JSON.stringify({
type: "notification",
msg: connectMsg
}));
}
}
ws.on("message", data => {
const message = JSON.parse(data);
console.log(`Received from client: ${message.name}: ${message.msg}`);
// Broadcast the message to all clients
for (let client of clients) {
if (client.readyState === ws.OPEN) {
client.send(JSON.stringify({
type: "message",
name: message.name,
msg: message.msg
}));
}
}
});
ws.on("close", () => {
clients.delete(ws);
console.log("Client disconnected");
// Notify all clients about the disconnection
const disconnectMsg = `유저 연결 해제 [현재 : ${clients.size}명]`;
for (let client of clients) {
if (client.readyState === ws.OPEN) {
client.send(JSON.stringify({
type: "notification",
msg: disconnectMsg
}));
}
}
});
});
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Websocket 실습</title>
<style>
#chat {
border: 1px solid #000;
height: 300px;
overflow-y: scroll;
margin-bottom: 10px;
padding: 10px;
}
.message {
padding: 5px;
border-bottom: 1px solid #ddd;
}
</style>
<script>
const ws = new WebSocket("ws://localhost:8001");
ws.onopen = () => {
console.log("Connected to server");
};
ws.onmessage = event => {
const message = JSON.parse(event.data);
const chat = document.getElementById("chat");
if (message.type === "message") {
chat.innerHTML += `<div class="message"><strong>${message.name}:</strong> ${message.msg}</div>`;
} else if (message.type === "notification") {
chat.innerHTML += `<div class="message"><em>${message.msg}</em></div>`;
}
chat.scrollTop = chat.scrollHeight; // Scroll to bottom
};
function sendMsg() {
const name = document.getElementById("name").value;
const msg = document.getElementById("msg").value;
if (name && msg) {
ws.send(JSON.stringify({ name, msg }));
document.getElementById("msg").value = ""; // Clear input
}
}
</script>
</head>
<body>
<h1>Websocket 실습 과제</h1>
<div id="chat"></div>
<input type="text" id="name" placeholder="Your name">
<input type="text" id="msg" placeholder="Your message">
<button onclick="sendMsg()">전송</button>
</body>
</html>
const { WebSocketServer } = require("ws");
wss.on("connection", ws => {
wss.on("connection", ws => { ... })는 새로운 클라이언트가 연결될 때마다 호출되는 콜백 함수.
wss.on("connection", ws => {
console.log("New client connected");
const connectMsg = `새로운 유저 접속 [현재 : ${clients.size}명]`;
for (let client of clients) {
if (client.readyState === ws.OPEN) {
client.send(JSON.stringify({
type: "notification",
msg: connectMsg
}));
}
}
wss.on("connection", (ws) => {
console.log("New client connected");
// 메시지 이벤트 처리
ws.on("message", (data) => {
const message = JSON.parse(data);
console.log(`Received message: ${message}`);
// 예: 메시지를 다시 클라이언트에게 보냄
ws.send(JSON.stringify({
type: "response",
msg: `You said: ${message.msg}`
}));
});
// 연결 종료 이벤트 처리
ws.on("close", () => {
console.log("Client disconnected");
});
// 오류 이벤트 처리
ws.on("error", (error) => {
console.error(`WebSocket error: ${error}`);
});
});
const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 8001 });
wss.on("listening", () => {
console.log("WebSocket server is listening on port 8001");
});
wss.on("connection", (ws) => {
console.log("New client connected");
// 클라이언트와의 통신을 여기서 설정합니다.
});
const express = require("express");
const app = express();
app.use(express.static("front"));
app.listen(8000, () => {
console.log(`HTTP server listening on port 8000`);
});