-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.cjs
51 lines (42 loc) · 1.26 KB
/
server.cjs
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
const express = require("express");
const http = require("http");
const SocketIO = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = SocketIO(server, {
cors: {
origin: "*",
},
});
io.on("connection", (socket) => {
console.log("A user connected:", socket.id);
socket.on("join", (roomName) => {
const room = io.sockets.adapter.rooms.get(roomName) || { size: 0 };
const numberOfClients = room.size;
if (numberOfClients === 0) {
socket.join(roomName);
socket.emit("created", roomName, socket.id);
} else if (numberOfClients === 1) {
socket.join(roomName);
io.to(roomName).emit("join", roomName);
socket.emit("joined", roomName, socket.id);
} else {
socket.emit("full", roomName);
}
});
socket.on("offer", (offer, roomName) => {
socket.to(roomName).emit("offer", offer);
});
socket.on("answer", (answer, roomName) => {
socket.to(roomName).emit("answer", answer);
});
socket.on("candidate", (candidate, roomName) => {
socket.to(roomName).emit("candidate", candidate);
});
socket.on("disconnect", () => {
console.log("User disconnected:", socket.id);
});
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});