Skip to content

Instantly share code, notes, and snippets.

@erfg12
Last active February 25, 2019 18:24
Show Gist options
  • Save erfg12/37e81ace706f4d1d83dd64ca587e12aa to your computer and use it in GitHub Desktop.
Save erfg12/37e81ace706f4d1d83dd64ca587e12aa to your computer and use it in GitHub Desktop.
NodeJS script for a simple TCP server
var net = require('net');
var PORT = 6969;
net.createServer(function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
sock.on('data', function(data) {
//console.log('RAW DATA RCVD: ' + sock.remoteAddress + ': ' + data);
var readData = data + '';
if (readData[readData.length -1] == '\0') { // check if end of msg (if last char is null)
var msg = readData.split('\0'); // split data at null
for (var i = 0, len = msg.length; i < len; i++) {
if (msg[i].length > 0) { // if not dead end, echo msg
console.log('MSG RCVD: ' + msg[i]);
sock.write(msg[i] + '\0');
}
}
} else {
readData += readData; // append to new data and wait for null char
}
});
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
sock.on('end', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
sock.on('error', (err) => {
console.log('TCP error', err)
})
}).listen(PORT);
console.log('Server listening on port ' + PORT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment