WebSocket에 대해서 (& Socket.IO)

🍑 클라이언트-서버가 연결을 유지하며 양방향(duplex) 실시간 통신을 위해서 웹 소켓이 생겨났다.

  • 웹 소켓은 HTTP의 단점을 보완하여 동영상 스트리밍이나 실시간 채팅, 온라인 게임과 같은 곳에서 사용되고 있다.
  • 웹 소켓 연결을 위해서 클라이언트와 서버간의 특정 HTTP 기반 WebSocket 핸드셰이크가 교환된다.
  • 소켓 통신의 방법에는 TCP와 UDP를 사용하는 방법이 있다.
  • TCP 연결을 위해서는 사전에 상대방의 IP 주소와 Port 번호를 알고 있어야 한다.
  • UDP는 빠르지만, 데이터의 전달을 보장하지 않는다.


🍅 Socket.IO는 Node.js의 WebSocket 용 라이브러리이다.

🍒 WebSocket과 함께 작동하는 라이브러리로 브라우저-서버간 이벤트 기반 통신을 제공한다.

npm install socket.io


Socket.IO를 사용하면, 브라우저 종류에 구애받지 않고 실시간 웹 소켓 통신을 할 수 있다.

  • 브라우저에서 실행되는 client side 라이브러리와 Node.js sever side 라이브러리 양쪽 모두의 설치가 필요하다.
  • HTTP는 단방향 통신이기에 구현하기 여러운 기능들이 있었고, 이를 해결하기 위해서 웹 소켓 통신을 사용한다.
  • 웹 소켓이 등장하기 이전에는 Polling과 같은 방법을 사용하였다.
  • 웹 소켓은 HTTP 통신과 마찬가지로 80번 포트를 사용한다.
  • 소켓 통신의 url은 ws:// 로 시작한다.
  • 소켓 통신으로 네트워크 과부하를 줄일 수 있다. 또한, HTTP 헤더의 크기도 줄일 수 있다.

🥕 http Long polling : 서버는 요청에 대한 응답을 계속 받을 수 있는 상태로, 요청을 보낸 뒤 계속 응답(새로운 데이터)을 기다린다. 기존의 polling 방식은 주기적으로 응답하는 것으로 http long polling과는 차이가 있다.

 

Socket.io 사용하기 (공식 문서 예제 참조)

- 서버

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

io.on("connection", (socket) => {
  console.log("a user connected");
  socket.on("CHAT", (msg) => {
    console.log("client message === ", msg);
  });
});

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

- 클라이언트

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Socket Client</title>
  </head>
  <body>
    <div>
      <h1>Socket Test</h1>
      <div>
        <p>hi</p>
        <button class="send-btn">Send Server Hi!</button>
      </div>
    </div>
    <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
    <script>
      const button = document.querySelector(".send-btn");
      const socket = io();
      button.addEventListener("click", (e) => {
        e.preventDefault();
        socket.emit("CHAT", "Hi! from client");
      });
    </script>
  </body>
</html>

서버를 킨 후 localhost:3000/ 으로 HTML 문서에 접근할 수 있다.

접근시, 서버에 로그가 찍히고 클라이언트의 버튼을 누르면, 메세지가 서버에 전달되어 로그가 기록되는 것을 확인할 수 있다.

 

Socket.IO: https://socket.io

 

Socket.IO

Reliable Rest assured! In case the WebSocket connection is not possible, it will fall back to HTTP long-polling. And if the connection is lost, the client will automatically try to reconnect.

socket.io

npm에서 다운받고자 한다면 서버는 socket.io, 클라이언트는 socket.io-client를 사용한다.