Thursday, March 22, 2018

NodeJS - telnet - create echo server

Let us create a echo server using Node. For this, Open the terminal of Node REPL:

~ $ node

This will open the node prompt. Now, let us include the 'net' module.

> var net = require('net');
undefined

Implement the echo server using the following code:

> var server = net.createServer(function(socket){socket.on('data', function(data){socket.write(data);});});
undefined

Now, turning on the listener at a particular port number:
> server.listen(3000);
Server {
  domain: 
   Domain {
     domain: null,
     _events: { error: [Function: debugDomainError] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] },
  _events: { connection: [Function] },
  _eventsCount: 1,
  _maxListeners: undefined,
  _connections: 0,
  _handle: 
   TCP {
     reading: false,
     owner: [Circular],
     onread: null,
     onconnection: [Function: onconnection],
     writeQueueSize: 0 },
  _usingSlaves: false,
  _slaves: [],
  _unref: false,
  allowHalfOpen: false,
  pauseOnConnect: false,
  _connectionKey: '6::::3000',
  [Symbol(asyncId)]: 196 }


In a new terminal window, connect to the localhost server using telnet:

$ telnet 127.0.0.1 3000
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
hey 
hey 
hello
hello

We can see that, our messages are being echoed back. Hence, our implementation of a echo server is successful. Hence, we now exit the Node REPL prompt.

> .exit
~ $ 

Now, let us observe the response the telnet window:

$ telnet 127.0.0.1 3000
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
hey 
hey 
hello
hello
Connection closed by foreign host.
 $ 


We see that the telnet connection got closed as expected.

No comments:

Post a Comment