프로젝트/UNY

socket.io 실시간 chat 구현 (react - Node.js) - (1)

Roothyo 2021. 7. 8. 17:32

채팅과 같은 통신 시스템은 2가지 Protocol 방식으로 나뉘어 진다.

TCP(Stream)방식 과 UDP(DataGram) 방식

2가지 방식에 대한 자세한 설명은 다음을 참조하기 바란다.(https://roothyo.tistory.com/5?category=952607)

 

간단하게 설명하자면,

 

TCP

- 신뢰성 있는 통신을 제공

- UDP에 비해 시간이 더 걸림.

- Stream 방식으로 통신

- smtp, http, ...

UDP

- TCP에 비해 지연시간이 거의 없음. 주로 반응속도가 중요한 시스템에 적용.

- 신뢰성 있는 통신을 제공하지 못함.

- DataGram 방식으로 통신

- 게임, 동영상, ... 등

 

실시간 채팅은 주로 TCP로 구성되며 위에 있는 메소드의 대한 각 설명은 다음과 같다.

 

socket() : 소켓 생성
bind() : 소켓에 주소 할당(IP, port)
listen() : 소켓이 연결을 받아들이기 위한 상태로 전환
connect() : 클라이언트에서 소켓 생성 후, server로 연결 요청
accept() : 클라이언트로부터의 연결 요청 수락
send(), recv() : 데이터 송수신
close() : 연결 종료

 

Node.js에서 실시간 채팅을 구현하는데 사용되는 모듈은 Socket.IO이며, 클라이언트에서 사용하려면 Socket.io-client를 사용하면 된다. Socket.IO는 브라우저와 서버 간의 실시간 양방향 이벤트 기반 통신을 가능하게하는 라이브러리이다.

https://socket.io/docs/v4/

 

Introduction

What Socket.IO isSocket.IO is a library that enables real-time, bidirectional and event-based communication between the browser and the server. It consists of: a Node.js server: Source | API a Javasc

socket.io

 

필자는 socket.io github에 있는 example(chat & create-react-app-example)과 socket.io docs를 사용하여, 채팅을 구현하였다. 

https://github.com/socketio/socket.io/

 

socketio/socket.io

Realtime application framework (Node.JS server). Contribute to socketio/socket.io development by creating an account on GitHub.

github.com