-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsockets.js
68 lines (56 loc) · 1.85 KB
/
sockets.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
const express = require('express');
const os = require('os');
const Firebase = require('firebase')
const config = require('./config.json');
const DB = Firebase
.initializeApp({
apiKey: config.firebase.key,
databaseURL: config.firebase.url
}).database()
const PORT = process.env.PORT || 3003;
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io').listen(http);
const ifaces = os.networkInterfaces();
const getUsers = room => Object.keys(io.sockets.adapter.rooms[room].sockets);
io.on('connection', function (socket) {
// Get all users in room
socket.on('ready', payload => {
const room = payload.room;
console.log(socket.room);
console.log(socket.id);
console.log('======');
if (socket.room) socket.leave(socket.room);
socket.join(room);
socket.room = room;
socket.owner = payload.owner;
io.to(room).emit('users', {
initiator: socket.id,
users: getUsers(room)
});
// Add user to list
DB.ref(`room/${room}/users`).set({ [socket.id]: true })
});
socket.on('close', userId => {
io.to(socket.room).emit('close', { userId, force: socket.owner });
if (userId === socket.id) socket.leave(socket.room);
// Remove user from list
DB.ref(`room/${socket.room}/users/${userId}`).remove()
});
// Signal to all local copies of peer
socket.on('signal', payload => {
io.to(payload.userId).emit('signal', {
userId: socket.id,
signal: payload.signal
});
});
socket.on('disconnect', () => {
if (socket.owner) DB.ref(`room/${socket.room}`).remove();
io.to(socket.room).emit('close', { userId: socket.id, force: socket.owner });
});
});
http.listen(PORT, function() {
Object.keys(ifaces).forEach(ifname =>
ifaces[ifname].forEach(iface =>
console.log('listening on', iface.address, 'and port', PORT)));
});