-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
41 lines (38 loc) · 962 Bytes
/
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
var ws = require("nodejs-websocket");
var server = ws.createServer(function(conn) {
console.log("New connection");
conn.on("text", function(str) {
console.log("Received " + str);
conn.sendText(str.toUpperCase() + "!!!");
try {
var i = parseInt(str, 10);
if (!isNaN(i)) {
var data = {
timestamp: new Date(),
value: i,
custom: true
};
console.log('Broadcasting custom value ' + i);
broadcast(server, JSON.stringify(data));
}
} catch (e) {}
});
conn.on("close", function(code, reason) {
console.log("Connection closed");
});
conn.on('error', function(err) {
console.error(err);
});
}).listen(8083);
setInterval(function() {
var data = {
timestamp: new Date(),
value: Math.floor(Math.random() * 10)
};
broadcast(server, JSON.stringify(data));
}, 500);
function broadcast(server, msg) {
server.connections.forEach(function(conn) {
conn.sendText(msg)
})
}