-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
37 lines (33 loc) · 1.43 KB
/
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
var config = require('./config.json');
var dgram = require('dgram');
var udpsocket = dgram.createSocket('udp4');
var val = require('./validation.js');
var nodeidx = 0;
var server = module.exports = {};
server.run = function() {
udpsocket.on('listening', function () {
var address = udpsocket.address();
console.log('UDP Server listening on ' + address.address + ":" + address.port + ' with PID ' + process.pid);
});
udpsocket.on('message', function (message, remote) {
// check message format
val.check(message, 3164, function(match){
// define target node
if (nodeidx > config.farm.nodes.length-1 ) {
nodeidx = 0;
}
var target = config.farm.nodes[nodeidx];
nodeidx++;
// send message to target node
var client = dgram.createSocket('udp4');
var node = {"host": target.split(":")[0], "port": parseInt(target.split(":")[1] || "514")};
client.send(message, 0, message.length, node.port, node.host, function (err, bytes) {
if (err) throw err;
console.log(process.pid + ' - UDP message sent to ' + node.host + ':' + node.port);
//console.log(process.pid + ' - '+ remote.address + ':' + remote.port + ' - ' + message);
client.close();
});
});
});
udpsocket.bind(config.server_port, config.server_host);
};