io.on('connection', function(socket) {});
클라이언트에서 접속하면 자동으로 이벤트가 발생한다.
socket.on('event',function(data){ });
socket.emit('event',{data});
연결되어 있는 클라이언트 소켓에 'event'이름으로 {data}를 보낸다.
socket.join(‘roon name’)
socket.leave(‘roon name’)
room을 사용하게되면 room안에 있는 클라이언트에게만 이벤트가 전송된다.
사용한 라이브러리
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.1",
"nodemon": "^2.0.19",
"socket.io": "^4.5.1"
}
const express = require("express");
const app = express();
const http = require("http");
const cors = require("cors");
const { Server } = require("socket.io");
app.use(cors());
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
console.log(`연결된 소켓 아이디: ${socket.id}`);
socket.on("join_room", (data) => {
socket.join(data);
console.log(`연결된 소켓 아이디: ${socket.id} room번호 : ${data}`);
});
socket.on("send_message", (data) => {
console.log("방번호: ", data.room, "서버로 전달 받은 데이터:", data);
socket.to(data.room).emit("receive_message", data);
});
socket.on("disconnect", () => {
console.log(`소켓 끊김: ${socket.id}`);
});
}); //소켓감지
server.listen(3001, () => {
console.log("서버실행중");
});
사용한 라이브러리
"socket.io-client": "^4.5.1",
부모컴포넌트에서

위와 같이 설정후 chat.js에 socket을 props로 전달
const Chat = ({ socket, username, room }) => {
const [Message, setMessage] = useState("");
const [history_data, set_history_data] = useState([]);
const send = async () => {
if (Message !== "") {
const messageData = {
room: room,
author: username,
message: Message,
time: new Date(Date.now()).getHours() + ":" + new Date(Date.now()).getMinutes(),
};
await socket.emit("send_message", messageData);
set_history_data((list) => [...list, messageData]); //내가 보낸 메시지도 히스토리에 쌓이게함
}
};
useEffect(() => {
socket.on("receive_message", (data) => {
console.log("서버에서 내려온 데이터", data);
set_history_data((history_data) => [...history_data, data]);
});
}, [socket]);
return (
<>
생략
<>
);
};
export default Chat;