Thursday, April 23, 2020

Node.js net module

Node.js net module

node.js net module


Node.js 'net' module defines an asynchronous network wrapper and provides a mechanism to create streams based TCP Client and TCP servers. This module can be used to perform the socket operations using Node.js.

This module can be accessed using,

var net = require('net');


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

This method produces a new TCP server. The connectionListener field is made a listener for the 'connection' event automatically.

net.connect(options[, connectionListener])

This is a factory method and returns a new 'net.Socket' object and connects to the provided address and port.

net.createConnection(options[, connectionListener])

This is a factory method and returns a new 'net.Socket' object and connects to the provided address and port number.

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

This factory method produces a TCP connection to a port on the host and returns ‘net.Socket’ object. If the host is not specified, the 'localhost' will be assumed. The connectListener field is added as a listener for the 'connect' event.

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

This factory method produces a TCP connection to a port on the host and returns a new 'net.Socket' object. If the host is not specified, the 'localhost' will be assumed. The connectListener field is added as a listener for the 'connect' event.

net.connect(path[, connectListener])

This factory method produces Unix socket connection to path and returns a new 'net.Socket'. The connectListener field is added as a listener for the 'connect' event.

net.createConnection(path[, connectListener])

This factory method produces a Unix socket connection to the path and returns a new 'net.Socket'. The connectListener field is added as a listener for the 'connect' event.

net.isIP(input)

This method checks if the input is an IP address. The method returns 0 for invalid strings, 4 for IPv4 addresses, and 6 for IPv6 addresses.

net.isIPv4(inputAddress)

This method returns true if the inputAddress is an IPv4 address, else returns false.

net.isIPv6(inputAddress)

This method returns true if the inputAddress is an  IPv6 address, else returns false.

net.Server class

 The Class, net.Sever is used to creating TCP and IPC servers

server.listen()

Server.listen() has following signatures,
  • server.listen(handle[, backlog][, callback])
  • server.listen(options[, callback])
  • server.listen(path[, backlog][, callback]) is used for IPC servers
  • server.listen([port[, host[, backlog]]][, callback])is used for TCP servers
The server can start to accept connections on the supplied parameters. If the host is not provided, the server accepts connections directed to any IPv4 address (INADDR_ANY). The port number is assigned zero to a random port. A TCP or an IPC server can be created using 'net.Sever' object. It just depends upon what it is listening to.

This function is asynchronous. The moment of time at which the server begins to listen, the 'listening' event is emitted. The callback parameter is added as a listener for the 'listening' event.

All listen() methods can be supplied with the backlog field to define the maximum length of the queue of pending connections. However, the actual length of the queue will be controlled by the OS using sysctl settings such as tcp_max_syn_backlog and somaxconn on Linux.

This parameter has 511 (not 512) as default value.

server.close([callback])

This method closes when all the opened connections and the 'close' event is emitted by the server.

server.address()

This method returns the address bounded to the server, the address family name, and the port number of the server as reported by the operating system.
.

server.unref()

Invoking the server.unref() method on a server enables the server to exit if this is the only active server in the event system. If the server is already unrefd, then calling unref again will not produce any effect.

server.ref()

This method is the opposite of server.unref() function. By calling ref on a previously unrefd server will not make the program to exit if it's the only server left (the default behavior). If the server is refd, then invoking the ref() method again will not produce any effect.

server.getConnections(callback)

It used to find the number of concurrent connections available on the server asynchronously. The method works when sockets are sent to forks. The callback(parameter) must be provided with two arguments err and count.

Events

listening

This event is emitted as the server is bounded after calling server.listen.

connection

This event is emitted when a new connection is established. Socket object, the connection object is available to the event handler. Socket is an instance of net.Socket.

close

This event is emitted when the server closes. Note that if connections exist, this event is not emitted until all the connections are ended.

error

This event is emitted when some error has occurred. The 'close' event is called automatically following this event.

The net.Socket class


The net.Socket class extends stream.Duplex, and is an abstraction of a TCP socket or a streaming IPC endpoint. The user can create and use the net.Socket object directly to communicate with a server.

The net.Socket object can also be created by Node.js and passed to the user when a connection is received. For example, this object passed to the listeners of a 'connection' event emitted on a net.Server, and then the user can use it to communicate with the client.

The net.Socket is an event emitter and emits following events,

lookup

This event is emitted after resolving the hostname but before connecting to the server. This event is not applied and used with UNIX sockets.

connect

The ‘connect’ event is emitted when a socket connection is successfully established.

data

The ‘data’ event is emitted upon the reception of the data. The data field will be a Buffer or String. The data is lost if no listener is available when the Socket emits the data event.

end

The ‘end’ event is emitted when the other end of the socket sends a FIN packet. This event ends the readable side of the socket.

timeout

The ‘timeout’ event is emitted if the socket is inactive beyond the timeout limit. The ‘timeout’ event is used to notify that the socket was idle beyond the timeout period. However, the user should close the connection manually.

drain

When the write buffer becomes empty, the ‘drain' event is emitted. The ‘drain’ event is emitted when the write buffer becomes empty. It can be used to control the flow of uploads.

error

The ‘error’ event is emitted when some error happens. The 'close' event will always follow this event.

close

The ‘close’ event is emitted if the socket is completely closed. The field hadError is a Boolean. This field is used to indicate that if the socket was closed due to a transmission error or it was closed normally.

Properties of net.Socket

  • bufferSize
  • remoteAddress
  • remoteFamily
  • remotePort
  • localAddress
  • localPort
  • bytesRead
  • bytesWritten

net.Socket methods


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

This method is used to open a connection for a specified socket. If the port number and host are supplied, then the socket will be opened as a TCP socket, if the host is not supplied, localhost will be assumed. If the path is supplied, the socket will be opened as a Unix socket to that path.

socket.connect(path[, connectListener])

This method is used to open a connection for a specified socket. If port number and the host are given, then the socket can be opened as a TCP socket. If host is not supplied, then localhost will be assumed. If a path is supplied, the socket will be opened as a Unix socket to that path.

socket.setEncoding([encoding])

This method is used to set the encoding for the socket.

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

This method is enables to send the data. The second parameter defines the encoding in the case of a string.

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

This method partially closes the socket. It means that it sends a FIN packet. However, the server may still send some data.

socket.destroy()

This method enables to makes sure that no further I/O activity happens on this socket. Necessary only in case of errors (parse error or so).

socket.pause()

This method is used to pause process of the reading the data. As result, the 'data' event will not be emitted. This method can be used to control the flow of upload.

socket.resume()

This pause() method can be resumed by calling to resume().

socket.setTimeout(timeout[, callback])

This method is used set the timeout period of the socket. The net.Socket does not set a timeout by default .

socket.setNoDelay([noDelay])

This method is used to disable the Nagle algorithm. By default, TCP connections use the Nagle algorithm, they buffer data before sending it off. Setting true for noDelay will immediately fire off data each time socket.write() is called. noDelay defaults to true.

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

This method is used to enable/disable keep-alive functionality. We can also and optionally set the initial delay before the first keepalive probe is sent on an idle socket. By default parameter enable is set to false.

socket.address()

This method returns tan object having the bound address, the family name of the address, and the port number of the socket as mentioned by the OS. This object has three properties as port: 12346, family: 'IPv4', and the address: '127.0.0.1'.

socket.unref()

This method is used to make a socket allow the program to exit in case of only one active socket in the event system. If the socket is already unrefd, then invoking socket.unref() will produce no effect.

socket.ref()

This method does the reverse process of socket.unref() method. By invoking socket.ref() on a previously unrefd socket will not make the program to exit in case of this is the only socket left. If the socket is already refd, then invoking socket.ref() again not produce any effect.

Example


We can create a simple client-server application for a demonstration.

First, create server.js

//include the 'net' module
//Server program
const net = require('net');
var myserver = net.createServer(function(connection) {
 console.log('The client connected successfully');

 connection.on('end', function() {
    console.log('The client is disconnected');
 });

 connection.write('Welcome to Node.js!\r\n');
 connection.pipe(connection);
});
//start listening
myserver.listen(3000, function() {
 console.log('server is listening');
});


Then. create client.js

//include the 'net' module
//Client program
const net = require('net');
var myclient = net.connect({port: 3000}, function() {
 console.log('The client is connected to server!'); 
});
//recieve data from the server
myclient.on('data', function(data) {
 console.log(data.toString());
 myclient.end();
});
//Disconnect
myclient.on('end', function() {
 console.log('The client is disconnected from server');
});


Now, run both these files in different Node.js command prompt windows. First, run server.js

Output:
(at server-side)
server is listening
The client connected successfully
The client is disconnected

(at client-side)
The client is connected to server!
Welcome to Node.js!

The client is disconnected from server



Credit and Reference:https://nodejs.org/api/net.html