forked from electricimp/Wiznet_5500
-
Notifications
You must be signed in to change notification settings - Fork 0
/
echo_server.js
executable file
·94 lines (73 loc) · 2.25 KB
/
echo_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
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
88
89
90
91
92
93
94
#!/usr/bin/env node
/**
* echo server
*
*/
const DEFAULT_PORT = 60000;
var net = require('net');
var cid = 1;
var started = new Date().getTime() / 1000;
var port = parseInt(process.argv[2]);
if (port <= 1024 || isNaN(port)) port = DEFAULT_PORT;
function log2(who, what) {
return function() {
var args = Array.prototype.slice.call(arguments);
// log('[%s on %s]', who, what, args);
};
};
function log() {
var now = new Date().getTime() / 1000;
var time = parseInt((now - started) % 10000);
var args = Array.prototype.slice.call(arguments);
args[0] = "[%d] " + args[0];
args.splice(1, 0, time);
console.log.apply(null, args);
}
function echo(socket) {
socket.id = cid++;
socket.on('data', function(data) {
log("Data[%d]: %s", socket.id, data.toString('hex').trim());
});
socket.on('timeout', function() {
log("Timeout!");
socket.destroy();
});
socket.on('error', function() {
log("Error!");
socket.destroy();
});
socket.on('end', function() {
log("End!");
socket.destroy();
});
socket.on('close', function() {
log("Close!");
server.getConnections(function(err, count) {
log("Disconnection from %s:%d, %d of %d open connections", socket.remoteAddress, socket.remotePort, socket.id, count);
})
});
socket.on('drain', () => null);
socket.pipe(socket);
server.getConnections(function(err, count) {
log("Connection from %s:%d to %s:%d, %d of %d open connections", socket.remoteAddress, socket.remotePort, socket.localAddress, socket.localPort, socket.id, count);
});
};
/**
* net.Server (http://nodejs.org/api/net.html#net_class_net_server)
* events: listening, connections, close, err
* methods: listen, address, getConnections,
*/
var server = net.createServer(echo);
server.listen({ host: "0.0.0.0", port: port });
server.on('listening', function() {
var ad = server.address();
log('Listening on %s:%s using %s', ad.address, ad.port, ad.family);
});
server.on('connection', function(socket) {
socket.setKeepAlive(true);
socket.setTimeout(90000);
});
server.on('error', function(err) {
log(err);
server.close(function() { log("shutting down the server!"); });
});