Upgrade: websocket을 포함한 요청을 서버에 보냄.GET /chat HTTP/1.1 헤더에 Connection: Upgrade, Upgrade: websocket 등 포함.101 Switching Protocols 응답을 보내면서, 기존 HTTP 연결을 웹소켓 프로토콜로 전환.send() 및 onmessage 이벤트를 통해 자유롭게 메시지 교환 가능.서버 측
Express
const express = require('express'); const app = express();ws 또는 Socket.IO
간단한 ws 사용 예시
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
console.log('클라이언트가 연결되었습니다.');
ws.on('message', (message) => {
console.log(`수신 메시지: ${message}`);
// 받은 메시지를 모든 클라이언트로 브로드캐스트
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(`서버 응답: ${message}`);
}
});
});
ws.send('웹소켓 연결이 성공적으로 이루어졌습니다.');
});
server.listen(3000, () => {
console.log('서버가 포트 3000에서 대기 중입니다.');
});
클라이언트 측 (HTML/JavaScript)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>웹소켓 예제</title>
</head>
<body>
<h1>웹소켓 채팅</h1>
<input id="inputMsg" type="text" placeholder="메시지 입력" />
<button id="sendBtn">전송</button>
<ul id="messages"></ul>
<script>
const ws = new WebSocket('ws://localhost:3000');
ws.onopen = () => {
console.log('웹소켓 연결 성공');
};
ws.onmessage = (event) => {
const li = document.createElement('li');
li.textContent = event.data;
document.getElementById('messages').appendChild(li);
};
document.getElementById('sendBtn').onclick = () => {
const msg = document.getElementById('inputMsg').value;
ws.send(msg);
document.getElementById('inputMsg').value = '';
};
</script>
</body>
</html>