YouTip LogoYouTip

Nodejs Net Module

[![Image 1: Java File](#)Node.js Built-in Modules](#) * * * Node.js's `net` module is a core module used for creating TCP or IPC-based servers and clients. It provides asynchronous networking capabilities and can be used to build various network applications, such as chat servers, proxy servers, etc. ### Main Features 1. Create TCP servers and clients 2. Create IPC (Inter-Process Communication) servers and clients 3. Handle network connections and data transmission 4. Manage the lifecycle of network connections * * * ## Basic Usage ### Creating a TCP Server ## Example const net = require('net'); // Create TCP server const server = net.createServer((socket)=>{ console.log('Client connected'); // Receive client data socket.on('data',(data)=>{ console.log(`Received data: ${data}`); socket.write(`Server received: ${data}`);// Send data to client }); // Client disconnects socket.on('end',()=>{ console.log('Client disconnected'); }); }); // Listen on port 3000 server.listen(3000,()=>{ console.log('Server listening on port 3000'); }); ### Creating a TCP Client ## Example const net = require('net'); // Create client and connect to server const client = net.createConnection({ port:3000},()=>{ console.log('Connected to server'); client.write('Hello Server!');// Send data to server }); // Receive server data client.on('data',(data)=>{ console.log(`Received server data: ${data}`); client.end();// Disconnect }); client.on('end',()=>{ console.log('Disconnected from server'); }); * * * ## Core API Details ### net.createServer([, connectionListener]) Creates a new TCP or IPC server. **Parameters:** * `options`: Optional configuration object * `allowHalfOpen`: Whether to allow half-open connections, defaults to false * `pauseOnConnect`: Whether to pause the socket on connection, defaults to false * `connectionListener`: Automatically set as a listener for the 'connection' event ### net.createConnection(options[, connectListener]) Creates a TCP connection to the specified port and host. **Common options:** * `port`: Port to connect to (required) * `host`: Host to connect to, defaults to 'localhost' * `localAddress`: Local interface to bind the network connection to * `family`: IP protocol family (4 or 6) * * * ## Network Socket (Socket) `net.Socket` is the core class of the net module, representing a network connection. ### Common Events 1. `connect`: Triggered when a connection is successfully established 2. `data`: Triggered when data is received 3. `end`: Triggered when the other end of the connection sends a FIN packet 4. `timeout`: Triggered when the connection times out due to inactivity 5. `error`: Triggered when an error occurs 6. `close`: Triggered when the socket is completely closed ### Common Methods 1. `write(data[, encoding][, callback])`: Sends data on the socket 2. `end([, encoding])`: Half-closes the socket 3. `destroy()`: Ensures no more I/O activity occurs on this socket 4. `pause()`: Pauses reading data 5. `resume()`: Resumes reading data * * * ## Advanced Applications ### Handling Multiple Client Connections ## Example const net = require('net'); const server = net.createServer((socket)=>{ // Set a unique ID for each connection socket.id=Date.now(); console.log(`Client ${socket.id} connected`); socket.on('data',(data)=>{ console.log(`Received data from client ${socket.id}: ${data}`); // Broadcast message to all clients server.getConnections((err, count)=>{ if(count >1){ socket.write(`There are ${count-1} other clients online`); } }); }); socket.on('end',()=>{ console.log(`Client ${socket.id} disconnected`); }); }); server.listen(3000); ### Timeout Handling ## Example const server = net.createServer((socket)=>{ // Set connection timeout to 5 minutes socket.setTimeout(5*60*1000); socket.on('timeout',()=>{ console.log('Connection timed out, disconnecting'); socket.end(); }); }); * * * ## Methods and Properties | Function | Description | | --- | --- | | Create Server | `net.createServer([, connectionListener])`: Used to create a TCP server that can listen for connection requests. | | Connect to Server | `net.connect(options[, connectListener])` or `net.createConnection(options[, connectListener])`: Used to connect to a specified server (create a client). | | Socket Object | The `socket` object represents a connection to a TCP server or client and contains various methods for sending, receiving, and closing connections. | ### Methods | No. | Method & Description | | --- | --- | | 1 | **net.createServer([, connectionListener])** Creates a TCP server. The connectionListener parameter automatically creates a listener for the 'connection' event. | | 2 | **net.connect(options[, connectionListener])** Returns a new 'net.Socket' and connects to the specified address and port. The 'connect' event will be triggered when the socket is established. | | 3 | **net.createConnection(options[, connectionListener])** Creates a TCP connection to port port and host host. host defaults to 'localhost'. | | 4 | **net.connect(port[, host][, connectListener])** Creates a TCP connection with port port and host host. host defaults to 'localhost'. The connectListener parameter will be added as a listener to the 'connect' event. Returns 'net.Socket'. | | 5 | **net.createConnection(port[, host][, connectListener])** Creates a TCP connection with port port and host host. host defaults to 'localhost'. The connectListener parameter will be added as a listener to the 'connect' event. Returns 'net.Socket'. | | 6 | **net.connect(path[, connectListener])** Creates a connection to the unix socket at path. The connectListener parameter will be added as a listener to the 'connect' event. Returns 'net.Socket'. | | 7 | **net.createConnection(path[, connectListener])** Creates a connection to the unix socket at path. The connectListener parameter will be added as a listener to the 'connect' event. Returns 'net.Socket'. | | 8 | **net.isIP(input)** Checks if the input is an IP address. Returns 4 for IPv4, 6 for IPv6, and 0 otherwise. | | 9 | **net.isIPv4(input)** Returns true if the input address is IPv4, otherwise returns false. | | 10 | **net.isIPv6(input)** Returns true if the input address is IPv6, 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])** Listens for connections on the specified port port and host host. By default, host accepts direct connections from any IPv4 address (INADDR_ANY). When port is 0, a random port is assigned. | | 2 | **server.listen(path[, callback])** Starts a local socket server by specifying the path connection. | | 3 | **server.listen(handle[, callback])** Connects via a specified handle. | | 4 | **server.listen(options[, callback])** The options properties: port port, host host, and backlog, along with the optional callback function, are called together as server.listen(port, , , ). Also, the path parameter can be used to specify a UNIX socket. | | 5 | **server.close()** The server stops accepting new connections but maintains existing connections. This is an asynchronous function; the server will close when all connections end and the 'close' event will be triggered. | | 6 | **server.address()** Returns the bound address, protocol family name, and server port from the operating system. | | 7 | **server.unref()** If this is the only active server in the event system, calling unref will allow the program to exit. | | 8 | **server.ref()** Opposite of unref. Calling ref on a server that was previously unrefed (if it is the only server) will prevent the program from exiting (default behavior). If the server is already refed, calling ref again has no effect. | | 9 | **server.getConnections(callback)** Asynchronously gets the number of current active connections for the server. Valid only after the socket is sent to a child process; the callback function has 2 parameters: err and count. | ### Events | No. | Event & Description | | --- | --- | | 1 | **listening** Triggered when the server calls server.listen to bind. | | 2 | **connection** Triggered when a new connection is created. socket is a net.Socket instance. | | 3 | **close** Triggered when the server closes. Note that if connections exist, this event will not be triggered until all connections are closed. | | 4 | **error** Triggered when an error occurs. The 'close' event will be called directly following 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 used when the user creates a client (using connect()), or created by Node and passed to the user via the connection server event. ### Events net.Socket events include: | No. | Event & Description | | --- | --- | | 1 | **lookup** Triggered after resolving the domain name but before connecting. Not applicable for UNIX sockets. | | 2 | **connect** Triggered when a socket connection is successfully established. | | 3 | **data** Triggered when data is received. | | 4 | **end** Triggered when the other end of the socket sends a FIN packet. | | 5 | **timeout** Triggered when the socket times out due to inactivity. Only indicates the socket has been idle. The user must manually close the connection. | | 6 | **drain** Triggered when the write buffer is empty. Can be used to control upload. | | 7 | **error** Triggered when an error occurs. | | 8 | **close** Triggered when the socket is completely closed. The parameter had_error is a boolean indicating whether the socket closed due to a transmission error. | ### Properties net.Socket provides many useful properties for controlling socket interaction: | No. | Property & Description | | --- | --- | | 1 | **socket.bufferSize** This property shows the number of bytes to be written to the buffer. | | 2 | **socket.remoteAddress** The remote IP address string, e.g., '74.125.127.100' or '2001:4860:a005::68'. | | 3 | **socket.remoteFamily** The remote IP protocol family string, e.g., 'IPv4' or 'IPv6'. | | 4 | **socket.remotePort** The remote port, represented numerically, e.g., 80 or 21. | | 5 | **socket.localAddress** The local IP address to which the network connection is bound, the local IP address the remote client is connecting to, represented as a string. For example, if you are listening on '0.0.0.0' and the client connects from '192.168.1.1', this value will be '192.168.1.1'. | | 6 | **socket.localPort** The local port address, represented numerically. E.g., 80 or 21. | | 7 | **socket.bytesRead** The number of bytes received. | | 8 | **socket.bytesWritten** The number of bytes sent. | ### Methods | No. | Method & Description | | --- | --- | | 1 | **new net.Socket()** Constructs a new socket object. | | 2 | **socket.connect(port[, host][, connectListener])** Creates a socket connection specifying the port port and host host. The host parameter defaults to localhost. Usually, you don't need to use net.createConnection to open a socket. Only used when you implement your own socket. | | 3 | **socket.connect(path[, connectListener])** Opens the unix socket at the specified path. Usually, you don't need to use net.createConnection to open a socket. Only used when you implement your own socket. | | 4 | **socket.setEncoding()** Sets the encoding. | | 5 | **socket.write(data[, encoding][, callback])** Sends data on the socket. The second parameter specifies the string encoding, default is UTF8 encoding. | | 6 | **socket.end([, encoding])** Half-closes the socket. For example, it sends a FIN packet. The server might still be sending data. | | 7 | **socket.destroy()** Ensures no I/O activity is happening on this socket. Only needed in case of errors (handling errors, etc.). | | 8 | **socket.pause()** Pauses reading data. That is, the data event will no longer be triggered. Very useful for controlling upload. | | 9 | **socket.resume()** Resumes reading data after calling pause(). | | 10 | **socket.setTimeout(timeout[, callback])** Sets the socket to timeout after being idle for more than timeout milliseconds. | | 11 | **socket.setNoDelay()** Disables the Nagle algorithm. By default, TCP connections use the Nagle algorithm, they buffer data before sending. Setting noDelay to true will send data immediately when socket.write() is called. noDelay defaults to true. | | 12 | **socket.setKeepAlive([, initialDelay])** Disables/enables keep-alive functionality, and sends the first
← Nodejs Domain ModuleNodejs Zlib Module β†’