-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (63 loc) · 2.14 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
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const port = 65515;
const fs = require('fs');
app.use('/client', express.static(__dirname + '/client'));
app.get('/', (req, res) => {
res.sendFile('/client/pages/index.html', {root: '.'});
});
let rooms = {};
io.on('connection', (socket) => {
socket.on('disconnect', () => {
if (socket.room) {
if (rooms.hasOwnProperty(socket.room) && rooms[socket.room].host === socket.id) {
if (rooms[socket.room].clients.length <= 0) { delete rooms[socket.room]; return; }
let index = rooms[socket.room].clients.indexOf(socket.id);
rooms[socket.room].host = rooms[socket.room].clients[0];
rooms[socket.room].clients.splice(socket.id, 1);
socket.to(socket.room).emit('User Left', socket.id);
} else {
let index = rooms[socket.room].clients.indexOf(socket.id);
rooms[socket.room].clients.splice(socket.id, 1);
socket.to(socket.room).emit('User Left', socket.id);
}
}
});
socket.on('Join', (code, username) => {
if (rooms.hasOwnProperty(code)) {
socket.room = code;
if (username) {
socket.username = username;
} else {
socket.username = "Anonymous";
}
rooms[code].clients.push(socket.id);
socket.join(code);
socket.to(code).emit('User Joined', socket.id, username);
} else {
socket.room = code;
if (username) {
socket.username = username;
} else {
socket.username = "Anonymous";
}
rooms[code] = { host: socket.id, clients: [] };
socket.join(code);
socket.to(code).emit("User Joined", socket.id, username);
}
});
socket.on('Send Offer', (id, desc) => {
socket.to(id).emit("Got Offer", socket.id, desc);
});
socket.on('Send Answer', (id, desc) => {
socket.to(id).emit("Got Answer", socket.id, desc);
});
socket.on('Send Candidate', (id, candidate) => {
socket.to(id).emit('Got Candidate', socket.id, candidate);
});
});
server.listen(port, () => {
console.log('Listening on localhost:' + port);
});