Web Programming TutorialsLearn How to Build Net Module Utility Modules in Nodejs

Learn How to Build Net Module Utility Modules in Nodejs

In this article, we are going to discuss about building a Net (Client-Server)) module utility by using one of the module present in the Node.js modules library. There are several modules present in Node.js library. They include OS module, path modules, net module, DNS module, and domain module. All of these modules are very popular and used very commonly to build any Node based application.

Node.js Net Module
In Node.js, the Net module provides basic utility functions to create both servers and clients. We can import this module that provides an asynchronous network wrapper by using the following syntax.

// Command to import Net Module in Node.js.

var net = require("net");

Methods present in the Net Module of node.js
The following are the basic methods and their descriptions, which are present in the Net Module of Node.js.

S No

Method

Description

1.

net.createServer ([options][, connectionListener])

This method of the Net module is used to create a new TCP server. When this method is called, then the ‘connectionListener’ argument is automatically set as a listener for the ‘connection’ event.

2.

net.connect (options[, connectionListener])

It is a factory method of the Net module that returns a new ‘net.Socket’ class instance and helps connect to the supplied address and port.

3.

net.createConnection (options[, connectionListener])

It is a factory method of the Net module that returns a new ‘net.Socket’ class instance and helps connect to the supplied address and port.

4.

net.connect(port[, host][, connectListener])

This method of the Net module is used to create a TCP connection to port on host. In case the host is omitted, then ‘localhost’ will be assumed. It will add the ‘connectListener’ parameter as a listener for the ‘connect’ event. It is also a factory method that returns a new ‘net.Socket’.

5.

net.createConnection (port[, host][, connectListener])

This method of the Net module is used to create a TCP connection to port on host. In case the host is omitted, then ‘localhost’ will be assumed. It will add the ‘connectListener’ parameter as a listener for the ‘connect’ event. It is also a factory method that returns a new ‘net.Socket’.

6.

net.connect (path[, connectListener])

This method of the Net module is used to create Unix socket connection to path. It will add the ‘connectListener’ parameter as a listener for the ‘connect’ event. It is also a factory method that returns a new ‘net.Socket’.

7.

net.createConnection (path[, connectListener])

This method of the Net module is used to create Unix socket connection to path. It will add the ‘connectListener’ parameter as a listener for the ‘connect’ event. It is also a factory method that returns a new ‘net.Socket’.

8.

net.isIP (input)

This method of the Net module is used to test if the input is an IP address. It will return 0 for invalid strings, 4 for IP version 4 addresses, and 6 for IP version 6 addresses.

9.

net.isIPv4 (input)

This method of the Net module is used to return true if the input is a version 4 IP address, otherwise it will return false.

10.

net.isIPv6 (input)

This method of the Net module is used to true if the input is a version 6 IP address, otherwise it will return false.

Net Module Class – net.Server
In Node.js Net module, this class is used to create a TCP or local server. It has the following are the basic methods and their descriptions.

S No

Method

Description

1.

server.listen (port[, host][, backlog][, callback])

This method of net.Server class is used to listen and accept connections on the specified port and host. In case the host is omitted, then the server will accept connections directed to any IPv4 address (INADDR_ANY). If tje port value is given as zero then it will assign a random port.

2.

server.listen (path[, callback])

This method of net.Server class is used to start a local socket server listening for connections on the given path.

3.

server.listen (handle[, callback])

This method of net.Server class is used to handle an object that can be set to either a server or socket (anything with an underlying _handle member), or a {fd: <n>} object.

This method will cause the server to accept connections on the specified handle, when the file descriptor or handle has already been bound to a port or domain socket (presumed). Windows do not support listening on a file descriptor.

4.

server.listen (options[, callback])

This method of net.Server class accepts the port, host, and backlog properties as options and the optional callback function. It behaves similarly as they do on a call to server.listen (port, [host], [backlog], [callback]) method discussed before.

5.

server.close ([callback])

This method of net.Server class is used to close the server instance when all connections are ended and the server has emitted a ‘close’ event.

6.

server.address ()

This method of net.Server class is used to return the bound address (i.e. the address family name and the port of the server as reported by the operating system).

7.

server.unref ()

Calling unref method of net.Server class on a server will allow the program to exit when this is the only active server in the event system. In case the server is already unrefd, and if we call unref again then it will have no effect.

8.

server.ref ()

This method of net.Server class works opposite of unref method, calling ref on a previously unrefd server will not let the program exit if it’s the only server left.

9.

server.getConnections (callback)

This method of net.Server class works asynchronously in order to get the number of concurrent connections on the server. It works when the sockets were sent to forks. It should be noted that the callback accepts two arguments err and count.

Events of Class – net.Server
The following are the events emitted by the net.Server class.

1.

close

This event is emitted by the net.Server class when the server closes.

2.

connection

This event is emitted by the net.Server class when a new connection is made.

3.

error

This event is emitted by the net.Server class when an error occurs.

4.

listening

This event is emitted by the net.Server class when the server has been bound after calling server.listen.

Net Module Class – net.Socket
In Node.js Net module, net.Socket instances implement a duplex Stream interface. Therefore, we can use it in two ways. Firstly, created by the user to use as a client with connect () method and secondly, created by the Node to pass to the user with the help of the ‘connection’ event of a server. It has the following are the basic methods and their descriptions.

S No

Method

Description

1.

new net.Socket([options])

This method of net.Socket class is used to construct a new socket object.

2.

socket.connect (port[, host][, connectListener])

This method of net.Socket class is used to open a connection for a given socket. When the parameter are given as port and host, then the socket will be opened as a TCP socket. When the host is omitted, then the localhost will be assumed.

3.

socket.connect(path[, connectListener])

This method of net.Socket class is used to open a connection for a given socket. When the parameter are given as port and host, then the socket will be opened as a TCP socket. When the host is omitted, then the localhost will be assumed.

4.

socket.setEncoding ([encoding])

This method of net.Socket class is used to set the encoding for the socket as a Readable Stream.

5.

socket.write (data[, encoding][, callback])

This method of net.Socket class is used to send data on the socket. The second parameter accepts the encoding format which defaults to UTF8 encoding.

6.

socket.end ([data][, encoding])

This method of net.Socket class is used to half-close the socket, i.e., it sends a FIN packet. The half-close means that the server can still send some data.

7.

socket.destroy()

This method of net.Socket class is used to ensure that no more I/O activity happens on this socket.

8.

socket.pause ()

This method of net.Socket class is used to pause the reading of data.

9.

socket.resume ()

This method of net.Socket class is used to resume reading after we made a call to pause () method.

10.

socket.setTimeout (timeout[, callback])

This method of net.Socket class is used to set the socket to timeout after a particular time in milliseconds of inactivity on the socket.

11.

socket.setNoDelay ([noDelay])

This method of net.Socket class is used to disable the Nagle algorithm.

12.

socket.setKeepAlive ([enable][, initialDelay])

This method of net.Socket class is used to enable or disable the keep-alive functionality.

13.

socket.address ()

This method of net.Socket class is used to return the bound address.

14.

socket.unref ()

This method of net.Socket class is used to call unref on a socket which allows the program to exit if this is the only active socket in the event system.

15.

socket.ref()

This method of net.Socket class is used to call ref on a previously unrefd socket will not let the program exit if it’s the only socket left. It works opposite to unref() method

Events of Class – net.Socket
The following are the events emitted by the net.Socket class.

S No.

Event

Description

1.

close

This event is emitted by the net.Socket once the socket is fully closed.

2.

connect

This event is emitted by the net.Socket when a socket connection is successfully established.

3.

data

This event is emitted by the net.Socket when data is received.

4.

drain

This event is emitted by the net.Socket when the write buffer becomes empty.

5.

error

This event is emitted by the net. Socket class when an error occurs.

6.

end

This event is emitted by the net.Socket when the other end of the socket sends a FIN packet.

7.

listening

This event is emitted by the net.Server class when the server has been bound after calling server.listen.

8.

lookup

This event is emitted by the net.Socket after resolving the hostname but before connecting.

9.

timeout

This event is emitted by the net.Socket if the socket times out from inactivity.

Example on use of Net Module in Node.js Application
In the following example, we are going to demonstrate the use of the above Net module methods. Like any other Node.js application, here we are going to create two js file named NetModuleServer.js (for server) and NetModuleClient.js (for client) which has the following code.

NetModuleServer.js

//Import net module from Node.js
var net = require('net');
var server = net.createServer(function(connection) { 
   console.log ('client has connected successfully!');
   
   connection.on('end', function() {
      console.log ('client has disconnected successfully!');
   });
   connection.write('Hello Node.js!\r\n');
   connection.pipe(connection);
});
server.listen(8067, function() { 
   console.log('server is listening');
   console.log('server bound address is: ' + server.address ());
});

NetModuleClient.js

//Import net module from Node.js
var net = require('net');
var client = net.connect({port: 8067}, function() {
   console.log ('Client has connected to server successfully!');  
});
client.on('data', function(data) {
   console.log(data.toString());
   client.end ();
});
client.on('end', function() { 
   console.log ('Client has disconnected from server successfully!');
});

Explanation of the code
In the above code, we have created a server and a client after importing net module of Node.js. For the Server, we are creating a connection and the communication channel through that connection. The server is listening for events from the client at the port 8067. Next, we have created client as a separate program which publishes the events to the server via port 8067. Client is logging the response received from server on ‘data’ and ‘end’ events as shown in the code above.

Output
When we execute the above Node.js programs in a sequence i.e. server program followed by the client program, then we will observe the following output on the console.

Client has connected to server successfully!
Hello Node.js!

Client has disconnected from server successfully!

Source code for the Net Module of Nodejs

To know more about Node.js functionality, in particular, how to set up sending emails, feel free to check this article.

Conclusion: –
In this article, we discussed the various methods present in the Net module of Node.js. We have imported the Net module and use the associated methods to build a Client-Server communication net utility.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -