Skip to content

Instantly share code, notes, and snippets.

@pujianto
Created April 20, 2019 07:56
Show Gist options
  • Save pujianto/6256ef44975e687bc011fd484873ce41 to your computer and use it in GitHub Desktop.
Save pujianto/6256ef44975e687bc011fd484873ce41 to your computer and use it in GitHub Desktop.
Minimal TCP socket server on Nodejs
const net = require('net');
const server = net.createServer( socket => {
socket.on('data', (data) => {
let message = data.toString('utf-8').trim();
console.log('incoming data ', message);
if (message === 'exit') {
let connectionName = socket.address().port + socket.address().address;
console.log('closing connection to ', connectionName);
socket.write('exiting...');
socket.destroy();
}
});
});
server.on('connection', socket => {
let connectionName = socket.address().port + socket.address().address;
console.log('incoming connection from ', connectionName);
});
const port = process.env.PORT || 8080;
const hostname = process.env.HOSTNAME || 'localhost';
server.listen(port, hostname);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment