-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.js
executable file
·88 lines (68 loc) · 2.19 KB
/
server.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
79
80
81
82
83
84
85
86
87
88
const path = require("path");
const express = require("express");
const httpolyglot = require("httpolyglot");
const app = express();
const port = process.env.PORT || 3013;
app.use(express.static(path.join(__dirname, "./", "dist")));
const httpsServer = httpolyglot.createServer({}, app);
const io = require("socket.io")(httpsServer, {
cors: {
origin: "http://localhost:3000", // used on dev environment
methods: ["GET", "POST"],
},
});
const rooms = {};
io.on("connect", (socket) => {
const query = socket.handshake.query;
const currentRoom = query.room;
const currentUser = query.user;
if (!rooms[currentRoom]) {
rooms[currentRoom] = {};
}
// Initiate the connection process as soon as the client connects
rooms[currentRoom][socket.id] = socket;
// Asking all other clients to setup the peer connection receiver
const peers = rooms[currentRoom];
for (const id in peers) {
if (id === socket.id) continue;
rooms[currentRoom][id].emit("initReceive", {
user: currentUser,
socketId: socket.id,
});
}
// Relay a peerconnection signal to a specific socket
socket.on("signal", (data) => {
if (!rooms[currentRoom][data.socketId]) return;
rooms[currentRoom][data.socketId].emit("signal", {
socketId: socket.id,
signal: data.signal,
});
});
// Send actions from user to other members
socket.on("action", (data) => {
for (const id in peers) {
if (id === socket.id) continue;
rooms[currentRoom][id].emit("action", {
action: data.action,
value: data.value,
socketId: socket.id,
});
}
});
// Remove the disconnected peer connection from all other connected clients
socket.on("disconnect", () => {
socket.broadcast.emit("removePeer", socket.id);
delete rooms[currentRoom][socket.id];
});
// Send message to client to initiate a connection the sender has already setup a peer connection receiver
socket.on("initSend", (data) => {
const initSocketId = data.socketId;
rooms[currentRoom][initSocketId].emit("initSend", {
user: currentUser,
socketId: socket.id,
});
});
});
httpsServer.listen(port, () => {
console.log(`Listening on port ${port}`);
});