Created
April 20, 2019 07:56
-
-
Save pujianto/6256ef44975e687bc011fd484873ce41 to your computer and use it in GitHub Desktop.
Minimal TCP socket server on Nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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