socket.io

rO_Or·2024년 1월 9일

간단한 공부

목록 보기
2/12

Socket.io?

Node.js를 이용하여 웹 어플리케이션에서 실시간 통신을 구현하기 위한 라이브러리.
웹소켓(WebSocket) 기반으로 작동하며, 지원되지 않는 브라우저에서는 폴링(Polling) 방식을 사용하여 통신을 한다.

설치

npm install socket.io

서버 구현하기

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);

io.on('connection', (socket) => {
  console.log('connected');
  
  socket.on('disconnect', () => {
    console.log('disconnected');
  });
};
http.listen(3000, () => {
  console.log('server start on 3000');
});

io.on('connection', func)은 클라이언트가 서버와 연결이 되면 실행된다.
disconnect는 클라이언트가 서버와 연결이 끊겼을 때 실행된다.

클라이언트 구현하기

npm install socket.io-client
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000');

socket.on('connect', () => {
  console.log('connected');
});

socket.on('disconect', () => {
  console.log('disconnected');
});

먼저 클라이언트용 패키지를 설치한 뒤, io 객체를 가져온다.
나머지 함수는 서버 때와 똑같다.

메시지 전송하기

// 서버 코드

io.on('connection', (socket) => {
  socket.on('chat msg', (msg) => {
    io.emit('chat msg', msg);
  });
});
// 클라이언트 코드

socket.emit('chat msg', msg);

socket.on('chat msg', (msg) => {
  console.log(msg);
});

socket.emit('chat msg', msg)에서 emit은 전송하는 역할을 하며, 인자로 전달되는 'chat msg'는 구분하는 키 값 같은 역할을 하게 된다.
socket.on('chat msg', (msg) ...에서 chat msg 키로 전달된 내용을 msg라는 인자로 받아온다.
그 다음 chat msg라는 키 값으로 msg를 다시 전송하여, 클라이언트가 받을 수 있게 된다.

join

socket.join(chat.room.toString());

socket들을 그룹으로 분리하고, 그 분리된 그룹에 들어갈 수 있도록 하는 함수가 join이다.

to

io.to(chat.room.toString()).emit('msg', cb)
위와 같이 함수를 작성하면 그룹에서 대화를 할 수 있다.

broadcast

socket.broadcast.to(chat.room.toString()).emit('msg', cb)
위와 같이 함수를 작성하면, 자신을 제외한 그룹에 접속된 사람들에게 전송된다.

leave

socket.leave(chat.room.toString());
위와 같이 함수를 작성하면, join했던 그룹을 떠난다.

profile
즐거워지고 싶다.

0개의 댓글