-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
server.js
99 lines (78 loc) · 2.65 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// https://www.webrtc-experiment.com/
var fs = require('fs');
// don't forget to use your own keys!
var options = {
// key: fs.readFileSync('fake-keys/privatekey.pem'),
// cert: fs.readFileSync('fake-keys/certificate.pem')
key: fs.readFileSync('/etc/letsencrypt/live/webrtcweb.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/webrtcweb.com/fullchain.pem')
};
// HTTPs server
var app = require('https').createServer(options, function(request, response) {
response.writeHead(200, {
'Content-Type': 'text/html'
});
var link = 'https://github.com/muaz-khan/WebRTC-Experiment/tree/master/socketio-over-nodejs';
response.write('<title>socketio-over-nodejs</title><h1><a href="'+ link + '">socketio-over-nodejs</a></h1><pre>var socket = io.connect("https://webrtcweb.com:9559/");</pre>');
response.end();
});
// socket.io goes below
var io = require('socket.io').listen(app, {
log: true,
origins: '*:*'
});
io.set('transports', [
// 'websocket',
'xhr-polling',
'jsonp-polling'
]);
var channels = {};
io.sockets.on('connection', function (socket) {
var initiatorChannel = '';
if (!io.isConnected) {
io.isConnected = true;
}
socket.on('new-channel', function (data) {
if (!channels[data.channel]) {
initiatorChannel = data.channel;
}
channels[data.channel] = data.channel;
onNewNamespace(data.channel, data.sender);
});
socket.on('presence', function (channel) {
var isChannelPresent = !! channels[channel];
socket.emit('presence', isChannelPresent);
});
socket.on('disconnect', function (channel) {
if (initiatorChannel) {
delete channels[initiatorChannel];
}
});
});
function onNewNamespace(channel, sender) {
io.of('/' + channel).on('connection', function (socket) {
var username;
if (io.isConnected) {
io.isConnected = false;
socket.emit('connect', true);
}
socket.on('message', function (data) {
if (data.sender == sender) {
if(!username) username = data.data.sender;
socket.broadcast.emit('message', data.data);
}
});
socket.on('disconnect', function() {
if(username) {
socket.broadcast.emit('user-left', username);
username = null;
}
});
});
}
// run app
app.listen(process.env.PORT || 9559);
process.on('unhandledRejection', (reason, promise) => {
process.exit(1);
});
console.log('Please open SSL URL: https://localhost:'+(process.env.PORT || 9559)+'/');