1. express ๋ก ์๋ฒ ๊ตฌ์ถ
- express ?
- node.js์ ํ๋ ์์ํฌ
- ์๋ฒ ์ฌ์ด๋ ํ๋ ์์ํฌ๋ก Node.js์ API๋ฅผ ๋จ์ํํ๊ณ , ์ฝ๊ฒ ์๋ฒ ๊ตฌ์ถ ๊ฐ๋ฅ
- express application์ผ๋ก๋ถํฐ http server ์์ฑ
import express from 'express';
import http from 'http';
const app = express();
const server = http.createServer(app);
2. http ์๋ฒ ์์, webSocket ์๋ฒ ๊ตฌ์ถ -> ๊ฐ์ ํฌํธ ์ด์ฉ
import ws from 'ws';
//http ์๋ฒ ์ ๋ฌ
const wss = new we.WebSocketServer({ server });
3. WebSocket Connection : ์๋ฒ -> ๋ธ๋ผ์ฐ์ ์ฐ๊ฒฐ
- socket.on() : socket์ผ๋ก๋ถํฐ ์จ ์ ๋ณด ์ ๊ณต
wss.on('connection', socket => {
console.log('Connected to Browser โ
');
socket.on('close', () => console.log('Disconnected from the Browser โ'))
socket.on('message', message => {
console.log(message.toString('utf8'));
});
socket.send('Hello!');
});
4. WebSocket Connection : ๋ธ๋ผ์ฐ์ -> ์๋ฒ ์ฐ๊ฒฐ
- socket.addEventListener()
//app.js
const socket = new WebSocket(`ws://${window.location.host}`);
socket.addEventListener('open', () => {
console.log('Connected to Server โ
');
});
socket.addEventListener('message', message => {
console.log('Just got this: ', message.data, ' from the server');
});
socket.addEventListener('close', () => {
console.log('Disconnected from Server โ');
});
setTimeout(() => {
socket.send('Hello from the Browser!');
}, 10000);
5. connection ํ์ธ
- server
- browser
'JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JavaScript] WebSocket vs Socket IO (1) | 2024.03.29 |
---|---|
[JavaScript] NodeJS, nodemon, babel | ํ๋ก์ ํธ Server Setup (0) | 2024.03.27 |
[JavaScript] padStart() : String ์๋ฆฌ ์ (0) | 2024.02.23 |