Node.js

웹소켓(WebSocket) 5장 - socket.io 라이브러리

blackbearwow 2023. 7. 21. 00:14

ws만 사용하며 통신을 구현한다면, 너는 결국 socket.io에 있는 기능을 새로 만들어야 한다(reconnection, acknowledgements, broadcasting 등). socket.io를 이용해 해당 기능들을 사용하면 쉽게 구현할 수 있다.

 

1. 설치

socket.io는 websocket구현이 아니다. 추가적인 metadata를 필요로 하기 때문에 서버와 클라이언트 둘다 라이브러리가 필요하다.

 

서버

npm install socket.io

 

클라이언트

<script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>

 

2. 간단한 예시

 

//index.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const {Server} = require("socket.io");
const io = new Server(server);

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
    console.log('index 렌더링');
});

io.on('connection', (socket) => {
    console.log('a user connected');
    socket.on('chat message', (msg) => {
        io.emit('chat message', msg);
    });
    socket.on('disconnect', () => {
        console.log('user disconnected');
    });
});

server.listen(3000, () => {
    console.log('listening on *:3000');
});

 

<!--index.html-->
<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }

      #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
      #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
      #input:focus { outline: none; }
      #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }

      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages > li { padding: 0.5rem 1rem; }
      #messages > li:nth-child(odd) { background: #efefef; }
    </style>
    <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
  </head>
  <body>
    <ul id="messages"></ul>
    <form id="form" action="">
      <input id="input" autocomplete="off" />
      <input type="submit">
    </form>
    <script>
      let socket = io();

      let messages = document.getElementById('messages');
      let form = document.getElementById('form');
      let input = document.getElementById('input');

      form.addEventListener('submit', function(e) {
        e.preventDefault();
        if (input.value) {
          socket.emit('chat message', input.value);
          input.value = '';
        }
      });

      socket.on('chat message', function(msg) {
        let item = document.createElement('li');
        item.textContent = msg;
        messages.appendChild(item);
        window.scrollTo(0, document.body.scrollHeight);
      })
    </script>
  </body>
</html>

결과

 

참고: https://socket.io/get-started/chat