Socket IO
- ์ค์๊ฐ, ์๋ฐฉํฅ, event ๊ธฐ๋ฐ์ ํต์ ์ ํ๋ framework
- webSocket์ ์์ ํต์ ์ ์ ๊ณตํ๋ ์ฌ๋ฌ ๋ฐฉ๋ฒ ์ค ํ๋
- Socket IO๋ webSocket์ ๋ถ๊ฐ๊ธฐ๋ฅ (X)
- Socket IO๋ ๊ฐ๋ webSocket์ ์ด์ฉ (O)
- ๋ง์ฝ webSocket ์ด์ฉ์ด ๋ถ๊ฐ๋ฅํ๋ฉด, Socket IO๋ ๋ค๋ฅธ ๋ฐฉ๋ฒ์ ์ด์ฉํด์ ๊ณ์ ์๋
- ์๋ ์ฌ์ฐ๊ฒฐ ์ง์, ์ฐ๊ฒฐ ๋๊น ํ์ธ, ๋ฐ์ด๋๋ฆฌ ์ง์
- ํ๋ ฅ์ฑ, ์ ๋ขฐ์ฑ
1. get socket server
- WebSocket
//server.js
const httpServer = http.createServer(app);
const wsServer = new ws. WebSocketServer({httpServer});
- Socket IO
- ์ ์ ์๊ฒ URL ์ ๊ณต : url/socket.io/socket.io.js -> front-end์์ ์ฝ๊ฒ ์ ๊ทผ ๊ฐ๋ฅ
//server.js
const httpServer = http.createServer(app);
const wsServer = SocketIO(httpServer);
2. connect to front
- WebSocket
//app.js
const socket = new WebSocket(`ws://${window.location.host}`);
- Socket IO
//app.js
const socket = io();
3. handle event
- WebSocket
- object -> string ๋ณํ ํ์
//app.js
socket.addEventListener('message', (message) => {
socket.send(message)
});
//server.js
wsServer.on('connection', socket => {
socket.on('message', (message) => {
const parsed = JSON.parse(message);
socket.send(parsed.payload);
});
});
- Socket IO
- event emit -> ํญ์ message ๋ณด๋ผ ํ์ X
- argument๋ก object ๊ฐ๋ฅ
- ์๋ฒ๋ก๋ถํฐ ์คํ๋๋ callback ํจ์๊ฐ front-end์์ ์คํ
//app.js
socket.emit('room', { payload: input.value }, () => {
//์๋ฒ๋ก ๋ถํฐ ์คํ๋๋ callback func
console.log('server is done');
});
//server.js
wsServer.on('connection', socket => {
socket.on('room', (msg, done) => {
console.log(msg);
done();
});
});
'JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JavaScript] WebSocket | ์๋ฒ์ ๋ธ๋ผ์ฐ์ ์ฐ๊ฒฐ (0) | 2024.03.28 |
---|---|
[JavaScript] NodeJS, nodemon, babel | ํ๋ก์ ํธ Server Setup (0) | 2024.03.27 |
[JavaScript] padStart() : String ์๋ฆฌ ์ (0) | 2024.02.23 |