a blog for those who code

Thursday 10 July 2014

Create TCP Server in Nodejs

We can create a basic TCP (Transmission Control Protocol) server and client with the Net module in Nodejs. It differs from the HTTP server in the way that rather than passing a requestListener, the TCP listens for incoming connections in an instance of socket.

That actually means that once the server socket is created, it listens for two events : when data is received and when the client closes the connection.

var a = require('net');
var server = a.createServer(function(conn) {
console.log('connected');

conn.on('data', function(data)) {
console.log(data + ' from ' + conn.remoteAddress + ' ' + conn.remotePort);
conn.write('Repeating ' + data);
});

conn.on('close', function() {

console.log('connection is closed');
});
}).listen(8081);

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment