Monday, 10 February 2014

Run server on Random Ports | NodeJS

Here, server.address() returns bound address, the family address, and the port of the server. Given below, 51134 is the randomly generated port.

Server | server.address()


var net = require('net');
var server = net.createServer(function (socket) {
  socket.end("goodbye\n");
});

// grab a random port.
server.listen(function() {
  address = server.address();
  console.log("opened server on %j", address);
});


| Run Server Node Application.

OUTPUT |
opened server on {"address":"0.0.0.0","family":"IPv4","port":51134}


Client | net.connect(options, [connectionListener])


var net = require('net');
var client = net.connect({port: 51134},
  function() { //'connect' listener
  console.log('client connected');
  client.write('world!\r\n');
});
client.on('data', function(data) {
  console.log(data.toString());
  client.end();
});
client.on('end', function() {
  console.log('client disconnected');
});


| Now, run the Client Node Application.

OUTPUT | Client-side
client connected
goodbye
client disconnected

No comments:

Post a Comment