-
Notifications
You must be signed in to change notification settings - Fork 91
/
app.js
72 lines (65 loc) · 1.68 KB
/
app.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
var express = require('express');
var app = express();
var fs = require('fs');
var open = require('open');
var options = {
key: fs.readFileSync('./fake-keys/privatekey.pem'),
cert: fs.readFileSync('./fake-keys/certificate.pem')
};
var serverPort = (process.env.PORT || 4443);
var https = require('https');
var http = require('http');
var server;
if (process.env.LOCAL) {
server = https.createServer(options, app);
} else {
server = http.createServer(app);
}
var io = require('socket.io')(server);
var roomList = {};
app.get('/', function(req, res){
console.log('get /');
res.sendFile(__dirname + '/index.html');
});
server.listen(serverPort, function(){
console.log('server up and running at %s port', serverPort);
if (process.env.LOCAL) {
open('https://localhost:' + serverPort)
}
});
function socketIdsInRoom(name) {
var socketIds = io.nsps['/'].adapter.rooms[name];
if (socketIds) {
var collection = [];
for (var key in socketIds) {
collection.push(key);
}
return collection;
} else {
return [];
}
}
io.on('connection', function(socket){
console.log('connection');
socket.on('disconnect', function(){
console.log('disconnect');
if (socket.room) {
var room = socket.room;
io.to(room).emit('leave', socket.id);
socket.leave(room);
}
});
socket.on('join', function(name, callback){
console.log('join', name);
var socketIds = socketIdsInRoom(name);
callback(socketIds);
socket.join(name);
socket.room = name;
});
socket.on('exchange', function(data){
console.log('exchange', data);
data.from = socket.id;
var to = io.sockets.connected[data.to];
to.emit('exchange', data);
});
});