-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
65 lines (55 loc) · 1.67 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
const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
const socket = require('socket.io');
const io = socket(server);
const rooms = {};
const PORT = process.env.PORT || 8000;
app.get('/user', function (req, res) {
console.log('/user request called');
res.send('Welcome to GeeksforGeeks');
});
io.on('connection', socket => {
/*
If a peer is initiator, he will create a new room
otherwise if peer is receiver he will join the room
*/
socket.on('join room', roomID => {
if (rooms[roomID]) {
// Receiving peer joins the room
rooms[roomID].push(socket.id);
} else {
// Initiating peer create a new room
rooms[roomID] = [socket.id];
}
/*
If both initiating and receiving peer joins the room,
we will get the other user details.
For initiating peer it would be receiving peer and vice versa.
*/
const otherUser = rooms[roomID].find(id => id !== socket.id);
if (otherUser) {
socket.emit('other user', otherUser);
socket.to(otherUser).emit('user joined', socket.id);
}
});
/*
The initiating peer offers a connection
*/
socket.on('offer', payload => {
io.to(payload.target).emit('offer', payload);
});
/*
The receiving peer answers (accepts) the offer
*/
socket.on('answer', payload => {
io.to(payload.target).emit('answer', payload);
});
socket.on('ice-candidate', incoming => {
io.to(incoming.target).emit('ice-candidate', incoming.candidate);
});
});
server.listen(PORT, e => {
console.log('Server is up and running on Port 8000');
});