socket.io

✒️ 2025-05-26 14:04 내용 수정


HTTP의 long-polling을 사용하는 web socket 라이브러리

1. Server 설정

  1. 먼저 VSC 터미널에서 socket.io를 다운 받는다.
npm install socket.io
  1. server.js 파일에서 express 서버와 연결하고, event listener를 추가한다.
    • 특정 event 발생 시 socket의 기능을 지정해준다.
// express 설정
const express = require("express");
const app = express();

// http와 socket.io 설정
const { createServer } = require("http");
const { Server } = require("socket.io");

const server = createServer(app); // express를 사용한 http 서버 생성
const io = new Server(server); // socket 서버 생성

io.on("connection", (socket) => { // listen on connection event
    console.log("websocket 연결 완료");

	// event를 emit -> 클라이언트에서 hello라는 이벤트 emit 시 hi 사용 가능
	socket.emit("hello", "hi");

    // test라는 이벤트 발생 시 이벤트 리스너
    socket.on("test", () => { // receiver
        console.log("test");
    });

});

server.listen(3000, () => {
	console.log('서버 접속 가능 : http://localhost:3000');
});

2. 클라이언트 설정

  1. ejs나 HTML에서 CDN으로 추가하거나, bundle 형태로 npm install socket.io-client를 사용하여 다운 받는다.
<script src="https://cdn.socket.io/4.7.5/socket.io.min.js" integrity="sha384-2huaZvOR9iDzHqslqwpR87isEmrfxqyWOF7hr7BY6KG0+hVKLoEXMPUJw3ynWuhO" crossorigin="anonymous"></script>
  1. 서버에서 사용한 것과 동일한 도메인을 사용한다면 script에 아래 문구를 추가한다.
const socket = io();
const socket = io("https://server-domain.com");