Websocket이란?
Websocket 사용법
client 폴더
// index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="index.js" defer></script>
<title>Document</title>
</head>
<body style="height: 100vh"></body>
</html>
// index.js
const ws = new WebSocket("ws://localhost:7071/ws");
server 폴더
//index.js
const WebSocket = require("ws");
const wss = new WebSocket.Server({ port: 7071 });
7071포트로 ws를 연결해준다.
서버를 실행하고 network를 확인해보면 핸드쉐이크 확인이 가능하다.
서버에서는 websockey token을 클라이언트에서 보내주는 websocket key를 이용해 랜덤하게 생성한다.
// index.js
const ws = new WebSocket("ws://localhost:7071/ws");
// server index.js에서 보내는 메시지와 객체 확인가능
ws.onmessage = (webSocketMessage) => {
console.log(webSocketMessage);
console.log(webSocketMessage.data);
};
// 마우스가 이동할 때마다 실시간으로 데이터를 서버에게 보내준다.
document.body.onmousemove = (event) => {
console.log(event);
const messageBody = {
x: event.clientX,
y: event.clientY,
};
ws.send(JSON.stringify(messageBody), console.log(event));
};
const WebSocket = require("ws");
const wss = new WebSocket.Server({ port: 7071 });
// 클라이언트에게 보내주는 메시지
wss.on("connection", (ws) => {
ws.send("connected");
// client에서 보내는 메시지 확인가능
ws.on("message", (messageFromClient) => {
const message = JSON.parse(messageFromClient);
console.log(message);
});
});