npm install socket.io
// With an HTTP server
import { createServer } from "http";
import { Server } from "socket.io";
const httpServer = createServer();
const io = new Server(httpServer, { /* options */ });
io.on("connection", (socket) => {
// ...
});
httpServer.listen(3000);
socket.io모듈은 내부적으로 /socket.io경로에 socket.io.js 파일을 자동으로 등록한다
// html
<script src="/socket.io/socket.io.js"></script>
// app.js
const socket = io();
이벤트는 개발자가 임의로 설정할 수 있다
// 해당 이벤트를 받고 콜백함수 실행
socket.on("받을 이벤트명", (msg) => {});
// 이벤트명 지정 후 메시지 전송
socket.emit("전송할 이벤트명", msg);
socket.emit()
원하는 수의 인자를 전송할 수 있으며 다양한 타입의 데이터를 전송할 수 있다
마지막 인자로 callback함수를 추가할 수 있다
// connection : 클라이언트와 연결함
io.on("connection", (socket) => {
// 클라이언트로부터 메시지 수신
socket.on("message", (data) => {
console.log(data); // Hello
// 클라이언트로 메시지 송신
socket.emit("new_message", "Hi");
});
// 여러개의 인자를 받을 수 있다
socket.on("arguments", (arg1, arg2, callack) => {
console.log(arg1); // "안녕"
console.log(arg1); // { arg:2 }
callback(); // 함수가 실행됨
});
// disconnectiong : 클라이언트와 연결이 끊어졌을 때 실행
socket.on("disconnecting", () => {})
});
// 서버로부터 메시지 수신
socket.on("new_message", (data) => {
console.log(data); // Hi
});
// 서버에 메시지 송신
socket.emit("message", "Hello");
// 여러개의 인자를 전송할 수 있다
socket.emit("안녕", { arg:2 }, () => {
console.log("이 함수는 프론트에서 실행됩니다.")
});
접속된 클라이언트들을 room으로 나눠서 관리할 수 있다
각 소켓들은 room에 join하고 leave할 수 있다
rooms는 서버만의 개념이다 (클라이언트는 접근 불가)

io.on("connection", (socket) => {
// 'some room'에 참여
socket.join("some room");
// to one room : "some room"에 인자 전달
io.to("some room").emit("Hello");
// to multiple rooms
io.to("room1").to("room2").to("room3").emit("hi");
// or with an array
io.to(["room1", "room2", "room3"]).emit("hi");
// 연결이 끊어졌으나 room에서 떠나지 않은 상태
socket.on("disconnecting", () => {
console.log(socket.rooms); // Set {...} -> socket ID
// 특정 room에 인자를 전달할 수 있다
socket.rooms.forEach((room) => {
socket.to(room).emit("bye");
});
});
// 연결이 완전히 끊어짐. room에서 떠난 상태
socket.on("disconnect", () => {
// socket.rooms.size === 0
});
});
다른 서버들 사이에 실시간 어플리케이션을 동기화 한다
다중 Socket.io 서버로 확장할 때, 이벤트가 모든 클라이언트로 적절하게 라우팅되도록 기본 메모리 내 어댑터를 다른 구현(implementation)으로 교체해야 한다
