
connection 클라이언트가 서버에 연결되었을 때 발생
disconnect 클라이언트가 연결을 해제했을 때 발생
disconnecting 클라이언트가 연결을 해제하려는 경우에 발생
error 연결 중에 오류가 발생했을 때 발생
// emit(전송할 이벤트 이름 [, 전송할 데이터])
// 전송할 데이터의 형태는 자유롭게 (문자열, 숫자, 객체)
socket.emit("hello", {
message: "안녕하세요"
})
// on을 이용해, 클라이언트에서 socket을 이용해서 보내준 데이터를
// 받을 이벤트를 등록함.
socket.on("hello", (res) => {
// res : socket을 이용해 보내준 데이터
console.log(res);
socket.emit("bye", { message: "안녕히 가세요~" });
});
npm install socket.io corsconst http = require("http");
const express = require("express");
const app = express();
// 소켓이 http모듈로 생성된 서버에서만 동작
const server = http.createServer(app);
const PORT = 8000;
// cors 이슈 : 다른 서버에서 보내는 요청을 제한함
const cors = require("cors");
app.use(cors());
const io = require("socket.io")(server, {
cors: {
origin: "http://localhost:3000",
},
});
server.listen(PORT, function () {
console.log(`Sever Open: ${PORT}`);
});
npm install socket.io-clientimport io from "socket.io-client";
const socket = io.connect("http://localhost:8000", { autoConnect: false });