-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
66 lines (49 loc) · 1.94 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
const express = require("express");
const socket = require("socket.io");
const app = express();
//Starts the server
let server = app.listen(9000, function () {
console.log("Server is running");
});
app.use(express.static("public"));
//Upgrades the server to accept websockets.
let io = socket(server);
//Triggered when a client is connected.
io.on("connection", function (socket) {
console.log("User Connected :" + socket.id);
//Triggered when a peer hits the join room button.
socket.on("join", function (roomName) {
let rooms = io.sockets.adapter.rooms;
let room = rooms.get(roomName);
//room == undefined when no such room exists.
if (room == undefined) {
socket.join(roomName);
socket.emit("created");
} else if (room.size == 1) {
//room.size == 1 when one person is inside the room.
socket.join(roomName);
socket.emit("joined");
} else {
//when there are already two people inside the room.
socket.emit("full");
}
console.log(rooms);
});
//Triggered when the person who joined the room is ready to communicate.
socket.on("ready", function (roomName) {
socket.broadcast.to(roomName).emit("ready"); //Informs the other peer in the room.
});
//Triggered when server gets an icecandidate from a peer in the room.
socket.on("candidate", function (candidate, roomName) {
console.log(candidate);
socket.broadcast.to(roomName).emit("candidate", candidate); //Sends Candidate to the other peer in the room.
});
//Triggered when server gets an offer from a peer in the room.
socket.on("offer", function (offer, roomName) {
socket.broadcast.to(roomName).emit("offer", offer); //Sends Offer to the other peer in the room.
});
//Triggered when server gets an answer from a peer in the room.
socket.on("answer", function (answer, roomName) {
socket.broadcast.to(roomName).emit("answer", answer); //Sends Answer to the other peer in the room.
});
});