forked from paulrouget/dzslides
-
Notifications
You must be signed in to change notification settings - Fork 1
/
slideserver.js
87 lines (73 loc) · 2.51 KB
/
slideserver.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
#!/usr/bin/env node
var WebSocketServer = require('./node_modules/websocket/lib/WebSocketServer');
var http = require('http');
var url = require('url');
var fs = require('fs');
var connectionArray = new Array();
var superConnectionID = null;
var nextID = Date.now();
var appendToMakeUnique = 1;
var server = http.createServer(function(request, response) {
console.log((new Date()) + " Received request for " + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function() {
console.log((new Date()) + " Server is listening on port 8080");
});
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: true
});
function getConnectionForID(id) {
var connect = null;
for (i=0; i<connectionArray.length; i++) {
if (connectionArray[i].clientID == id) {
connect = connectionArray[i];
break;
}
}
return connect;
}
wsServer.on('connect', function(connection) {
console.log((new Date()) + " Connection accepted.");
console.log("connectionArray.length: " + connectionArray.length);
if (connectionArray.length == 0){
superConnectionID = nextID;
console.log("superConnectionID: " + superConnectionID);
}
connectionArray.push(connection);
// Send the new client its token; it will
// respond with its login username.
connection.clientID = nextID;
nextID++;
var msg = {
type: "id",
id: connection.clientID
};
connection.sendUTF(JSON.stringify(msg));
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log("Received Message: " + message.utf8Data);
// Process messages
var sendToClients = false;
var msg = JSON.parse(message.utf8Data);
if (msg.id == superConnectionID)
sendToClients = true;
var connect = getConnectionForID(msg.id);
// Convert the message back to JSON and send it.
if (sendToClients) {
var msgString = JSON.stringify(msg);
for (i=0; i<connectionArray.length; i++) {
connectionArray[i].sendUTF(msgString);
}
}
}
});
connection.on('close', function(connection) {
connectionArray = connectionArray.filter(function(el, idx, ar) {
return el.connected;
});
console.log((new Date()) + " Peer " + connection.remoteAddress + " disconnected.");
});
});