-
Notifications
You must be signed in to change notification settings - Fork 1
/
socket.js
55 lines (47 loc) · 1.35 KB
/
socket.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
// requires socket.io
// http://socket.io/
var http = require('http'),
io = require('socket.io'), // for npm, otherwise use require('./path/to/socket.io')
server = http.createServer(function(req, res){
// your normal server code
res.writeHeader(200, {'Content-Type': 'text/html'});
res.end('<h1>Astronode</h1>');
});
server.listen(8080);
// socket.io
var socket = io.listen(server), controllerId;
socket.on('connection', function(client) {
console.log("new client connect "+ client.sessionId);
if (typeof controllerId == 'undefined') {
controllerId = client.sessionId;
client.send(JSON.stringify(true));
} else {
client.send(JSON.stringify(false));
}
client.on('message', function(message) {
// TODO: broadcast to specific clients
var data;
try {
data = JSON.parse(message);
} catch(e) {
console.log(message);
console.error(e.message);
}
if (client.sessionId == controllerId && Array.isArray(data) ) {
client.broadcast(JSON.stringify(data));
console.log('controller sent: ', message);
} else {
console.dir(data);
client.broadcast(JSON.stringify({
isRight: !data.isRight,
tel: data.tel
}));
}
}) ;
client.on('disconnect', function(){
console.log('client disconnected', client.sessionId);
if (client.sessionId == controllerId) {
controllerId = undefined;
}
});
});