포도가게의 개발일지

Socket vs WebSocket vs Socket.IO? 본문

Socket vs WebSocket vs Socket.IO?

grape.store 2021. 11. 26. 23:14
반응형

1. Socket 이란?

- 소켓(Socket)이란 네트워크상에서 서버와 클라이언트 두개의 프로그램이 특정 포트를 통해 양방향 통신이 가능하도록 만들어주는 소프트웨어 장치(파일)라 말할수 있다.

- 소켓은 "접속의 끝 부분"으로 정의된다. 

- 기술

tcp stream socket

 

2. WebSocket 이란?

why?

- 웹 소켓이 등장하기 전인 http 통신만으로는 data전송에 한계가 있었을것이다. 왜냐하면 request없이는 response를 줄 수 없기때문에 서버가 클라이언트한테 원하고자 할 때 데이터를 줄 수 가 없어서 생겼을것 같다.

How?

- 그러면 기존의 http통신가 어떻게 달라 socket의 연결상태를 유지할수있는가?

- 서버와 클라이언트 간의 WebSocket연결은 HTTP프로토콜을 통해 이루어집니다.(handshake) 

- 클라이언트 요청: upgrade : http 프로토콜을 전환하기 위해 사용하는 헤더. 웹소켓 요청 시에는 반드시 websocket이라는 값을 가지며, 이 값이 없거나 다른 값이면 cross-protocol attack이라고 간주하여 웹소켓 접속을 중지시킵니다.  

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com

- 서버 응답:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

 

- socket 기술을 이용하지만 http와 다르게 전이중 통신이 가능

- Web Socket은 Stateful protocol

 

 

 

2. Socket.io 란?

 

- 서버와 브라우저(client)간에 커뮤니케이션을 real time으로 가능하게 해주는 WebSocket 프로토콜을 편하게 사용하고자 만든 library

 

## client ##

const socket = io("ws://localhost:3000");

socket.on("connect", () => {
  // either with send()
  socket.send("Hello!");

  // or with emit() and custom event names
  socket.emit("salutations", "Hello!", { "mr": "john" }, Uint8Array.from([1, 2, 3, 4]));
});

// handle the event sent with socket.send()
socket.on("message", data => {
  console.log(data);
});

// handle the event sent with socket.emit()
socket.on("greetings", (elem1, elem2, elem3) => {
  console.log(elem1, elem2, elem3);
});
## server ##

const io = require("socket.io")(3000);

io.on("connection", socket => {
  // either with send()
  socket.send("Hello!");

  // or with emit() and custom event names
  socket.emit("greetings", "Hey!", { "ms": "jane" }, Buffer.from([4, 3, 3, 1]));

  // handle the event sent with socket.send()
  socket.on("message", (data) => {
    console.log(data);
  });

  // handle the event sent with socket.emit()
  socket.on("salutations", (elem1, elem2, elem3) => {
    console.log(elem1, elem2, elem3);
  });
});

 

WebSocket vs Socket.IO

WebSocket

  • HTML5 웹 표준 기술
  • 매우 빠르게 작동하며 통신할 때 아주 적은 데이터를 이용함
  • 이벤트를 단순히 듣고, 보내는 것만 가능함

Socket.io

  • 표준 기술이 아니며, 라이브러리임
  • 소켓 연결 실패 시 fallback을 통해 다른 방식으로 알아서 해당 클라이언트와 연결을 시도함
  • 방 개념을 이용해 일부 클라이언트에게만 데이터를 전송하는 브로드캐스팅이 가능함

socket.io room

 

'' 카테고리의 다른 글

[Web] SSE(Server Sent Event)  (0) 2022.03.26
Restful API?  (0) 2022.01.18
Flask pyJWT token 사용법  (0) 2021.07.30
url parameter 주고 받는법  (0) 2021.07.27
JSON이란?  (0) 2021.07.12
Comments