This is a TCP server for receiving data from GPS server
const net = require('net');
const lora_packet = require('lora-packet');
const clients = [];
const server = net.createServer(function (socket) {
socket.name = socket.remoteAddress + ":" + socket.remotePort;
socket.device = new Device(socket);
clients.push(socket);
let bufferString = '';
socket.on('data', function (data) {
try {
const packet = lora_packet.fromWire(data, 'hex');
const str = packet._packet.PHYPayload.toString('hex');
let prev = 0, next;
while ((next = str.indexOf('0d0a', prev)) > -1) {
bufferString += str.substring(prev, next + 4);
console.log('got whole message: ' + bufferString);
//Use the parts variable for futher communication
socket.device.emit('data',bufferString);
bufferString = '';
prev = next + 4;
}
bufferString += str.substring(prev);
} catch (err) {
console.log("DATA RECEIVING PRODUCED AN ERROR" + err);
}
});
socket.on('end', function () {
clients.splice(clients.indexOf(socket), 1);
});
})
// .listen(8080);
process.on('uncaughtException', function (err) {
console.log('something terrible happened..')
console.log(err);
})
module.exports = server;
I am using a TCP server to communicate to GPS devices and establish a live-connection with them.
I have a query that how would I load balance a TCP server to avoid a single point of failure? The problem is that when a TCP connection is formed, the data packets aren't delimited automatically and so I parse the whole stream to check "0d0a" delimiter.
const str = packet._packet.PHYPayload.toString('hex');
let prev = 0, next;
while ((next = str.indexOf('0d0a', prev)) > -1) {
bufferString += str.substring(prev, next + 4);
console.log('got whole message: ' + bufferString);
//Use the parts variable for futher communication
socket.device.emit('data',bufferString);
bufferString = '';
prev = next + 4;
}
Shouldn't I make this connection sticky to a particular server instance if I load balance my TCP server because I also store client connections in a local instance?
const clients = [];
Also, as node.js is an application server and not a web server, it's usually recommended that a web server should be used for reverse-proxying but how can I implement Apache or Nginx or HAproxy for that matter to suffice my use case?
If I don't use any front-end web-server, are there any consequences that have to be faced?