-
Notifications
You must be signed in to change notification settings - Fork 171
/
server.js
executable file
·62 lines (61 loc) · 2.18 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
const express = require('express');
const path = require('path');
const fs = require('fs');
const http = require('http');
const https = require('https');
const sio = require('socket.io');
const favicon = require('serve-favicon');
const compression = require('compression');
const app = express(),
options = {
key: fs.readFileSync(__dirname + '/rtc-video-room-key.pem'),
cert: fs.readFileSync(__dirname + '/rtc-video-room-cert.pem')
},
port = process.env.PORT || 3000,
server = process.env.NODE_ENV === 'production' ?
http.createServer(app).listen(port) :
https.createServer(options, app).listen(port),
io = sio(server);
const { rooms } = io.of('/').adapter;
// compress all requests
app.use(compression());
app.use(express.static(path.join(__dirname, 'dist')));
app.use((req, res) => res.sendFile(__dirname + '/dist/index.html'));
app.use(favicon('./dist/favicon.ico'));
// Switch off the default 'X-Powered-By: Express' header
app.disable('x-powered-by');
io.on('connection', socket => {
let room = '';
// sending to all clients in the room (channel) except sender
socket.on('message', message => socket.broadcast.to(room).emit('message', message));
socket.on('find', () => {
const url = socket.request.headers.referer.split('/');
room = url[url.length - 1];
const sr = rooms.get(room);
if (sr === undefined) {
// no room with such name is found so create it
socket.join(room);
socket.emit('create');
} else if (sr.size === 1) {
socket.emit('join');
} else { // max two clients
socket.emit('full', room);
}
});
socket.on('auth', data => {
data.sid = socket.id;
// sending to all clients in the room (channel) except sender
socket.broadcast.to(room).emit('approve', data);
});
socket.on('accept', async (id) => {
const [ socket ] = await io.in(id).fetchSockets();
socket.join(room);
// sending to all clients in 'game' room(channel), include sender
io.in(room).emit('bridge');
});
socket.on('reject', () => socket.emit('full'));
socket.on('leave', () => {
// sending to all clients in the room (channel) except sender
socket.broadcast.to(room).emit('hangup');
socket.leave(room);});
});