기존 HTTP 요청은 클라이언트에서 서버로 요청을 보내고 응답을 받는 프로토콜
서버에서 요청없이 응답을 보낼 수가 없었다. 또한 실시간 데이터 전송이 가능하다.
이를 웹소켓은 가능하게 할 수 있다.
socket.html
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>웹소켓 실습</title>
</head>
<body>
<script>
const ws = new WebSocket('ws://localhost:8981');
ws.onerror = console.error;
ws.onopen = function open() {
ws.send('연결 성공');
ws.send('클라이언트에서 서버로');
};
ws.onmessage = (e) => {
console.log(e);
};
</script>
</body>
</html>
socket.js
const http = require('http');
const { WebSocketServer } = require('ws');
const fs = require('fs').promises;
const path = require('path');
const server = http.createServer(async (req, res) => {
const data = await fs.readFile(path.join(__dirname, 'socket.html'));
res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"'});
res.end(data);
});
server.listen(8981, () => {
console.log('8981 포트에서 서버 실행 중');
});
// 아래를 통째로 주석처리하면 서버가 웹소켓을 지원하지 않을 경우 어떻게 되는지 확인할 수 있어요.
const wss = new WebSocketServer({ server });
wss.on('connection', (ws) => {
ws.on('error', console.error);
ws.on('message', (data) => {
console.log(data.toString());
});
setInterval(() => {
ws.send('매초 서버에서 클라이언트로 데이터 보내기');
}, 1000);
});
'네트워크' 카테고리의 다른 글
HTTP / 1.1, HTTP2, HTTP3 (0) | 2024.04.15 |
---|---|
HTTP(HyperText Transfer Protocol) (0) | 2024.04.12 |
OSI 7 계층 (0) | 2024.04.12 |