-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
74 lines (59 loc) · 2.26 KB
/
server.ts
File metadata and controls
74 lines (59 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { createServer } from "http";
import next from "next";
import { Server } from "socket.io";
import { generateRoomId } from "./utils";
const app = next({ dev: process.env.NODE_ENV !== "production" });
const handler = app.getRequestHandler();
const rooms: { [key: string]: string[] } = {}; // ✅ 채팅방 목록 관리
app.prepare().then(() => {
const httpServer = createServer(handler);
const io = new Server(httpServer, {
path: "/socket.io",
cors: { origin: "*" },
transports: ["websocket"],
});
io.on("connection", (socket) => {
console.log("✅ Client connected:", socket.id);
// ✅ 채팅방 입장 (유저 ID 기준으로 고유한 채팅방 ID 생성)
socket.on("joinRoom", ({ user1, user2 }) => {
const roomId = generateRoomId(user1, user2);
if (!rooms[roomId]) {
rooms[roomId] = [];
}
if (!rooms[roomId].includes(socket.id)) {
rooms[roomId].push(socket.id);
}
socket.join(roomId);
console.log(`🔗 ${socket.id} joined room: ${roomId}`);
});
socket.on("leaveRoom", (roomId) => {
if (!rooms[roomId]) {
console.log("❌ 존재하지 않는 채팅방입니다:", roomId);
return;
}
delete rooms[roomId]; // ✅ 서버에서 채팅방 제거
console.log(`🗑 채팅방 삭제됨: ${roomId}`);
});
// ✅ 채팅 메시지 전송 (송신자를 제외하고 메시지 전달)
socket.on("message", ({ user1, user2, msg }) => {
const roomId = generateRoomId(user1, user2); // ✅ 올바른 채팅방 ID 유지
if (!rooms[roomId]?.includes(socket.id)) {
console.error("❌ User is not in the room!");
return;
}
console.log(`📩 Message received in ${roomId}:`, msg);
// ✅ 송신자에게는 메시지를 보내지 않음 (중복 출력 방지)
socket.to(roomId).emit("message", { roomId, msg });
});
// ✅ 클라이언트 연결 종료 처리
socket.on("disconnect", () => {
console.log("❌ Client disconnected:", socket.id);
for (const roomId in rooms) {
rooms[roomId] = rooms[roomId].filter((id) => id !== socket.id);
}
});
});
httpServer.listen(3000, () => {
console.log(`🚀 Server ready on http://localhost:3000`);
});
});