Skip to content

Instantly share code, notes, and snippets.

@maikelsperandio
Created January 25, 2020 13:23
Show Gist options
  • Save maikelsperandio/70a718b45ae232fdee943eb738df7e72 to your computer and use it in GitHub Desktop.
Save maikelsperandio/70a718b45ae232fdee943eb738df7e72 to your computer and use it in GitHub Desktop.
A class to connect to a server by tcp
const net = require('net');
const port = 7070;
const host = '127.0.0.1';
const server = net.createServer();
server.listen(port, host, () => {
console.log('TCP Server is running on port ' + port + '.');
});
let sockets = [];
server.on('connection', function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
sockets.push(sock);
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress + ': ' + data);
// Write the data back to all the connected, the client will receive it as data from the server
sockets.forEach(function(sock, index, array) {
sock.write(sock.remoteAddress + ':' + sock.remotePort + " said " + data + '\n');
});
});
// Add a 'close' event handler to this instance of socket
sock.on('close', function(data) {
let index = sockets.findIndex(function(o) {
return o.remoteAddress === sock.remoteAddress && o.remotePort === sock.remotePort;
})
if (index !== -1) sockets.splice(index, 1);
console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment