웹소켓 예제.
웹소켓 예제.
서버 쪽 코드
// express, ws 객체 생성
const express = require("express");
const ws = require("ws");
const app = express();
app.use("/", function(req, res){
res.sendFile(__dirname + '/index.html')
})
const httpServer = app.listen(3001, () => {
console.log("서버가 3001번 포트로 동작합니다.");
});
const webSocketServer = new ws.Server({
server: httpServer,
});
webSocketServer.on("connection", (ws, request) => {
// 연결한 클라이언트 ip 확인
const ip = request.socket.remoteAddress;
console.log(`클라이언트 [${ip}] 접속`);
// 연결이 성공
if (ws.readyState === ws.OPEN) {
console.log(`[${ip}] 연결 성공`);
}
// html 페이지의 클라이언트로부터 메시지를 받았을 때 이벤트 처리
ws.on("message", (msg) => {
console.log(`${msg} [${ip}]`);
//서버가 html의 클라이언트에게 메시지를 보내는 처리.
ws.send(`${msg} 메세지를 확인했어요.`);
});
// 에러 처리
ws.on("error", (error) => {
console.log(`에러 발생 : ${error} [${ip}]`);
});
// 연결 종료 처리
ws.on("close", () => {
console.log(`[${ip}] 연결 종료`);
});
});
클라이언트 쪽 코드 .
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>web socket </title>
</head>
<body>
<div>
<input type="text" id="message" />
<button id="send"> 메시지 보내기 </button>
<button type="button" onclick="sendMessage()"> 전송 </button>
</div>
<div></div>
</body>
</html>