forked from millo-L/Typescript-ReactJS-WebRTC-1-1-P2P
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (64 loc) · 1.94 KB
/
index.js
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
75
76
77
78
let express = require("express");
let http = require("http");
let app = express();
let cors = require("cors");
let server = http.createServer(app);
let socketio = require("socket.io");
let io = socketio.listen(server);
app.use(cors());
const PORT = process.env.PORT || 8080;
let users = {};
let socketToRoom = {};
const maximum = 2;
io.on("connection", (socket) => {
socket.on("join_room", (data) => {
if (users[data.room]) {
const length = users[data.room].length;
if (length === maximum) {
socket.to(socket.id).emit("room_full");
return;
}
users[data.room].push({ id: socket.id });
} else {
users[data.room] = [{ id: socket.id }];
}
socketToRoom[socket.id] = data.room;
socket.join(data.room);
console.log(`[${socketToRoom[socket.id]}]: ${socket.id} enter`);
const usersInThisRoom = users[data.room].filter(
(user) => user.id !== socket.id
);
console.log(usersInThisRoom);
io.sockets.to(socket.id).emit("all_users", usersInThisRoom);
});
socket.on("offer", (sdp) => {
console.log("offer: " + socket.id);
socket.broadcast.emit("getOffer", sdp);
});
socket.on("answer", (sdp) => {
console.log("answer: " + socket.id);
socket.broadcast.emit("getAnswer", sdp);
});
socket.on("candidate", (candidate) => {
console.log("candidate: " + socket.id);
socket.broadcast.emit("getCandidate", candidate);
});
socket.on("disconnect", () => {
console.log(`[${socketToRoom[socket.id]}]: ${socket.id} exit`);
const roomID = socketToRoom[socket.id];
let room = users[roomID];
if (room) {
room = room.filter((user) => user.id !== socket.id);
users[roomID] = room;
if (room.length === 0) {
delete users[roomID];
return;
}
}
socket.broadcast.to(room).emit("user_exit", { id: socket.id });
console.log(users);
});
});
server.listen(PORT, () => {
console.log(`server running on ${PORT}`);
});