JavaScript

[JavaScript] WebSocket vs Socket IO

jjingle 2024. 3. 29. 11:27

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();
  });
});