-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (49 loc) · 1.59 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
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = 8888;
var clients = {};
io.on('connection', (socket) => {
console.log("Server detect a connection")
//Add user to connected clients
clients[socket.handshake.query.userId] = {
name:socket.handshake.query.name,
surname:socket.handshake.query.surname,
jobTitle:socket.handshake.query.jobTitle,
socket:socket
}
socket.on('join', function (data) {
console.log("Connection")
console.log(data)
socket.join(data.roomId);
socket.room = data.roomId;
const sockets = io.of('/').in().adapter.rooms[data.roomId];
if (sockets.length === 1) {
socket.emit('init')
} else {
if (sockets.length === 2) {
io.to(data.roomId).emit('ready')
} else {
socket.room = null
socket.leave(data.roomId)
socket.emit('full')
}
}
});
socket.on('signal', (data) => {
io.to(data.room).emit('desc', data.desc)
})
socket.on('disconnect', () => {
const roomId = Object.keys(socket.adapter.rooms)[0]
if (socket.room) {
io.to(socket.room).emit('disconnected')
}
//Remove user from connected clients
Object.keys(clients).forEach(userId=>{
if (clients[userId].socket ===socket){
delete clients[userId]
}
})
})
});
server.listen(port, () => { console.log("Server is listening") });