Websocket

공부의 기록·2022년 2월 3일
0

Node.JS

목록 보기
14/32
post-thumbnail

Introduce

본 문서는 2022년 2월 3일 에 작성되었습니다.

Web Socket Tech 를 적용하기 위한 모듈 2가지를 소개하고 있습니다.

  1. 간단하게 사용할 수 있는 ws 모듈
  2. 복합적인 설정이 편리한 WebSocket.io 모듈

Installation

npm i ws

npm i socket.io@2


Thoery

다음의 내용을 포함하고 있습니다.

🤔 WebSocket Tech 는 무엇인가 ?
🤔 Server Sent Events 는 무엇인가 ?

🤔 Web Socket Tech ?

Web Socket 은 HTML5 에 새로 추가된 스팩으로,
실시간 양방향 데이터 전송을 위한 기술입니다.

다음과 같은 모듈을 사용합니다.

  1. ws 프로토콜
  2. socket.io
  3. 기타

유사한 기술로는 SSE, Server Sent Events 가 있습니다.

🤔 SSE, Server Sent Events ?

Server Sent Events 는 EventSource 라는 객체를 사용하여,
서버에서부터 지속적으로 데이터를 전송받는 기술입니다.


✅ ws

ws 는 Web Socket 를 사용하기 위한 모듈 중 하나입니다.
여러 내장 함수들로 조금 더 간편하게 사용할 수 있습니다.

Web Socket 은 기본적으로 양방향 통신 이기 때문에,
Server, WebSocket 과 Client, WebSocket 이 모두 필요합니다.

ws.readyState

WebSocket Tech 에는 4가지 상태가 있습니다.

  1. CONNECTING (연결 중)
  2. OPEN (열림)
  3. CLOSING (닫는 중)
  4. CLOSED (닫힘)

Serever > websocket.js

import WebSocket from "ws";

const socket=(server)=>{
  const wss=new WebSocket.Server({ server });
  
  wss.on("connection", (ws,req)=>{
    const ip=req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    console.log("new Client Come in!", ip);
    
    // ws Server 가 메세지를 받으면 실행
    ws.on("message", (message)=>{
      console.log(message.toString());
    });
    
    // ws Server 가 닫히면 실행
    ws.on("close", ()=>{
      conosle.log("Client Get out!", ip);
      clearInterval(ws.interval);
    });
    
    // 3*1000 ms 마다 메세지 전달
    ws.interval=setInterval(()=>{
      if(ws.readyState === ws.OPEN) {
        ws.send("서버에서 클라이언트로 메세지를 보냅니다."):
      }
    }, 3000);
    
  });
};

export default socket;

Client > websocket_front.js

const webSocket=new WebSocket("ws://localhost:PORT");
webSockect.onopen=function() {
  console.log(event.data);
}

webSocket.onmessage=function(event) {
  console.log(event.data);
  webSocket.send("클라이언트에서 서버로 답장을 보냅니다.");
}

✅ WebSocket.io

Server > socket.js

import SocketIO from "socket.io");

const socket=(server)=>{
  const io=SocketIO(server, { path: "/socket.io" });
  io.on("Connection", (socket)=>{
    const req=socket.request;
    const ip=req.headers["x-forwarded-for"] || req.connection.remoteAddress;
    
    console.log("새로운 클라이언트 접속!", ip, socket.id, req.ip);
    
    socket.on("error", (error)=> {
      console.log(error);
    });
    
    socket.on("reply", (data)=> {
      console.log(data);
    });
    
    socket.interval=setInterval(()=>{
      socket.emit("news", "Hello, Socket.io";
    },3000);
  });
};

Client > websocket_front.js

const socket=io.connect("http://localhost:PORT", {
  socket.on("news", function (data) {
    console.log(data);
    socket.emit("reply", "Hello, Node.JS");
  });
});

Adv > 558p ~ 576p

profile
2022년 12월 9일 부터 노션 페이지에서 작성을 이어가고 있습니다.

0개의 댓글