Node.js Net Module
The Node.js Net module provides utilities for low-level network communication, including methods to create servers and clients. You can include this module using the following:
var net = require("net")
Methods
No. | Method & Description |
---|---|
1 | net.createServer([options][, connectionListener]) <br>Creates a TCP server. The connectionListener parameter automatically sets up a listener on the 'connection' event. |
2 | net.connect(options[, connectionListener]) <br>Returns a new 'net.Socket' and connects to the specified address and port. <br>A 'connect' event is emitted once the socket is established. |
3 | net.createConnection(options[, connectionListener]) <br>Creates a TCP connection to the port and host. The host defaults to 'localhost'. |
4 | net.connect(port[, host][, connectListener]) <br>Creates a TCP connection to the specified port and host. The host defaults to 'localhost'. The connectListener parameter is added as a listener to the 'connect' event. Returns 'net.Socket'. |
5 | net.createConnection(port[, host][, connectListener]) <br>Creates a TCP connection to the specified port and host. The host defaults to 'localhost'. The connectListener parameter is added as a listener to the 'connect' event. Returns 'net.Socket'. |
6 | net.connect(path[, connectListener]) <br>Creates a connection to the specified path of a Unix socket. The connectListener parameter is added as a listener to the 'connect' event. Returns 'net.Socket'. |
7 | net.createConnection(path[, connectListener]) <br>Creates a connection to the specified path of a Unix socket. The connectListener parameter is added as a listener to the 'connect' event. Returns 'net.Socket'. |
8 | net.isIP(input) <br>Tests if input is an IP address. Returns 4 for IPv4, 6 for IPv6, and 0 for any other format. |
9 | net.isIPv4(input) <br>Returns true if the input is an IPv4 address, otherwise returns false. |
10 | net.isIPv6(input) <br>Returns true if the input is an IPv6 address, otherwise returns false. |
net.Server
net.Server is typically used to create a TCP or local server.
No. | Method & Description |
---|---|
1 | server.listen(port[, host][, backlog][, callback]) <br>Starts a server listening for connections on the specified port and host. By default, the host accepts connections on any IPv4 address (INADDR_ANY). A random port is assigned if port is 0. |
2 | server.listen(path[, callback]) <br>Starts a local socket server listening for connections on the specified path. |
3 | server.listen(handle[, callback]) <br>Starts a server listening for connections on the specified handle. |
4 | server.listen(options[, callback]) <br>The options object includes properties like port, host, and backlog, along with an optional callback function, which together call server.listen(port, [host], [backlog], [callback]). Additionally, the path parameter can specify a UNIX socket. |
5 | server.close([callback]) <br>Stops the server from accepting new connections and keeps existing connections. This function is asynchronous, and the server will be closed when all connections are ended and the server emits a 'close' event. |
6 | server.address() <br>Returns the bound address, the address family name, and port of the server as reported by the operating system. |
7 | server.unref() <br>Calling unref on a server will allow the program to exit if this is the only active server in the event system. |
8 | server.ref() <br>Opposite of unref, calling ref on a previously unrefed server will not let the program exit if it's the only server left (default behavior). If the server is already refed, calling ref again will have no effect. |
9 | server.getConnections(callback) <br>Asynchronously gets the number of concurrent connections on the server. Works when sockets were sent to forks. Callback with two arguments: err and count. |
Events
Number | Event & Description |
---|---|
1 | listening <br>Emitted when the server has been bound after calling server.listen. |
2 | connection <br>Emitted when a new connection is made. socket is an instance of net.Socket. |
3 | close <br>Emitted when the server closes. Note that if connections exist, this event is not emitted until all connections are ended. |
4 | error <br>Emitted when an error occurs. The 'close' event will be called right after this event. |
net.Socket
The net.Socket object is an abstraction of a TCP or UNIX socket. net.Socket instances implement a duplex stream interface. They can be created by the user and used as a client (with connect()), or they can be created by Node.js and passed to the user through the connection event of a server.
Events
Events of net.Socket include:
Number | Event & Description |
---|---|
1 | lookup <br>Emitted after resolving the hostname but before connecting. Not applicable for UNIX sockets. |
2 | connect <br>Emitted when a connection is established successfully. |
3 | data <br>Emitted when data is received. |
4 | end <br>Emitted when the other end of the socket sends a FIN packet. |
5 | timeout <br>Emitted if the socket times out from inactivity. It's just to notify that the socket has been idle. The user must manually close the connection. |
6 | drain <br>Emitted when the write buffer becomes empty. Can be used to throttle uploads. |
7 | error <br>Emitted when an error occurs. |
8 | close <br>Emitted once the socket is fully closed. The parameter had_error is a boolean which says if the socket was closed due to a transmission error. |
Properties
net.Socket provides several properties to interact with the socket:
Number | Property & Description |
---|---|
1 | socket.bufferSize <br>This property shows the number of bytes in the write buffer. |
2 | socket.remoteAddress <br>The string representation of the remote IP address, e.g., '74.125.127.100' or '2001:4860:a005::68'. |
3 | socket.remoteFamily <br>The string representation of the remote IP protocol family, e.g., 'IPv4' or 'IPv6'. |
4 | socket.remotePort <br>The numeric representation of the remote port, e.g., 80 or 21. |
5 | socket.localAddress <br>The local interface to which the network connection is bound. The local IP address string that the remote client is connecting on. |
6 | socket.localPort <br>The numeric representation of the local port address, e.g., 80 or 21. |
7 | socket.bytesRead <br>The number of bytes received. |
8 | socket.bytesWritten <br>The number of bytes sent. |
Methods
Number | Method & Description |
---|---|
1 | new net.Socket([options]) <br>Constructs a new socket object. |
2 | socket.connect(port[, host][, connectListener]) <br>Specifies the port and host to create a socket connection. The host parameter defaults to localhost. Generally, there is no need to use net.createConnection to open a socket. This is only necessary if you implement your own socket. |
3 | socket.connect(path[, connectListener]) <br>Opens a Unix socket at the specified path. Generally, there is no need to use net.createConnection to open a socket. This is only necessary if you implement your own socket. |
4 | socket.setEncoding([encoding]) <br>Sets the encoding |
5 | socket.write(data[, encoding][, callback]) <br>Sends data on the socket. The second parameter specifies the encoding of the string, defaulting to UTF8. |
6 | socket.end([data][, encoding]) <br>Half-closes the socket. For example, it sends a FIN packet. The server may still be sending data. |
7 | socket.destroy() <br>Ensures that no I/O activity occurs on this socket. This is only necessary in case of errors. (Error handling, etc.) |
8 | socket.pause() <br>Pauses the reading of data. This means no 'data' events will be emitted. Useful for controlling uploads. |
9 | socket.resume() <br>Resumes reading data after calling pause(). |
10 | socket.setTimeout(timeout[, callback]) <br>Sets the socket to timeout after idle for timeout milliseconds. |
11 | socket.setNoDelay([noDelay]) <br>Disables the Nagle algorithm. By default, TCP connections use the Nagle algorithm, buffering data before sending it. Setting noDelay to true will send data immediately on socket.write(). The default value for noDelay is true. |
12 | socket.setKeepAlive([enable][, initialDelay]) <br>Disables/enables the keep-alive functionality and optionally sets the initial delay before the first keep-alive probe is sent on an idle socket. The default is false. <br>Set initialDelay (in milliseconds) to set the delay between the last data packet received and the first keep-alive probe. Setting initialDelay to 0 will maintain the default (or previously set) value. The default value is 0. |
13 | socket.address() <br>Returns the bound address, protocol family name, and port from the operating system. The returned object has 3 properties, such as { port: 12346, family: 'IPv4', address: '127.0.0.1' }. |
14 | socket.unref() <br>Calling unref on the server will allow the program to exit if this is the only active server in the event system. If the server is already unref'd, calling unref again will have no effect. |
15 | socket.ref() <br>Opposite to unref, calling ref on a previously unref'd server will not let the program exit if it's the only server left (default behavior). If the server is already ref'd, calling ref again will have no effect. |
Example
Create a server.js file with the following code:
var net = require('net');
var server = net.createServer(function(connection) {
console.log('client connected');
connection.on('end', function() {
console.log('client closed the connection');
});
connection.write('Hello World!\r\n');
connection.pipe(connection);
});
server.listen(8080, function() {
console.log('server is listening');
});
Run the server code:
$ node server.js
server is listening # Server is created and listening on port 8080
Open a new terminal window and create a client.js file with the following code:
var net = require('net');
var client = new net.Socket();
client.connect(8080, '127.0.0.1', function() {
console.log('Connected');
client.write('Hello from client');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
Run the client code:
$ node client.js
Connected
Received: Hello World!
Connection closed
var net = require('net');
var client = net.connect({port: 8080}, function() {
console.log('Connected to the server!');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('Disconnected from the server');
});
Executing the above client code:
Connected to the server!
Hello World!
Disconnected from the server