-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcpServerBlinkTest.js
84 lines (61 loc) · 1.95 KB
/
tcpServerBlinkTest.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
/*
SOURCE: https://gist.github.com/tedmiston/5935757
In the node.js intro tutorial (http://nodejs.org/), they show a basic tcp
server, but for some reason omit a client connecting to it.
And connect with a tcp client from the command line using netcat, the *nix
utility for reading and writing across tcp/udp network connections. I've only
used it for debugging myself.
$ netcat 127.0.0.1 1337
MODIFIED FOR SAVING INPUT DATA TO A FILE
*/
var _ = require('c-struct');
var soh_t = {
length : 0,
id : 1,
delay: 250
};
var _soh_t = new _.Schema({
length : _.type.uint8,
id : _.type.uint8,
delay : _.type.uint8
});
_.register('soh_t', _soh_t);
//Log
var log = require('./utils/logger.js').Logger;
//Config
var config = require('./config.json');
var net = require('net');
//Interval
var interval;
var server = net.createServer(function(socket) { //Callback function called when 'connection' event of net is called
log("New connection", "info");
createInterval(socket);
socket.on('data', function (input) {
soh_t.delay = input.readUIntLE(0, 1);
log("Received data: " + soh_t.delay.toString(), "info");
//Changing delay of interval
clearInterval(interval);
createInterval(socket);
});
socket.on('end', function () {
log("Connection terminated", "info");
clearInterval(interval);
});
socket.on('error', function () {
log("Connection terminated caused by error", "info");
clearInterval(interval);
});
});
server.listen(config.web_port, config.web_host);
console.log("Listening on port " + config.web_port + " on " + config.web_host);
function createInterval(socket) {
interval = setInterval(function () {
soh_t.length = Object.keys(soh_t).length;
var buff = _.packSync('soh_t', {
length : soh_t.length,
id : soh_t.id,
delay : soh_t.delay
});
socket.write(buff);
}, 500);
}