Introduction
ofnet
The module provides an asynchronous network API for implementing TCP servers and clients. It is the core of network functions and provides basic support for upper-level modules such as HTTP, HTTPS, etc. This tutorial will be fully introducednet
Using methods and best practices for modules.
Introducing the net module
const net = require('net');
Core concept
TCP (Transmission Control Protocol)
TCP is a connection-oriented, reliable, byte stream-based transport layer communication protocol.net
The module mainly deals with TCP communication.
Socket
Socket is the endpoint of network communication, expressed inInstance of class. It can be a connection established between the server and the client, or it can be a connection actively created by the client.
server
Server usageClass creation, responsible for listening to connections and processing client requests.
TCP server creation
Basic Server
const net = require('net'); // Create a serverconst server = ((socket) => { ('Client connected'); // Receive data ('data', (data) => { (`Received data: ${data}`); // Send a response ('The server has received your message'); }); // Connection closed ('end', () => { ('Client disconnected'); }); // Handle errors ('error', (err) => { ('Connection error:', err); }); }); // Listen to the port(3000, () => { ('The server starts successfully, listen to port 3000'); });
Server configuration options
Configuration options can be passed when creating a server:
const server = ({ allowHalfOpen: false, // Automatically send FIN when the other end sends a FIN packet (default) pauseOnConnect: false // Whether to pause the socket while connecting (default)});
Server Events
Class inherits from
EventEmitter
, supports the following major events:
-
listening
: Triggered when the server starts listening for connection -
connection
: Triggered when a new client connection is established -
error
: Triggered when an error occurs -
close
: Triggered when the server is closed
('listening', () => { ('The server starts listening for connection'); }); ('connection', (socket) => { ('New Client Connection'); }); ('error', (err) => { ('Server Error:', err); }); ('close', () => { ('The server is closed'); });
TCP client creation
Basic Client
const net = require('net'); // Create a connectionconst client = ({ host: 'localhost', port: 3000 }, () => { ('Connected to the server'); // Send data ('Hello, server'); }); // Receive data('data', (data) => { (`Received a server response: ${data}`); // Close the connection (); }); // End of connection('end', () => { ('Disconnected to the server'); }); // Error handling('error', (err) => { ('Connection error:', err); });
Client configuration options
There are several configuration options that can be passed when creating a client connection:
const client = ({ host: 'localhost', // Host name port: 3000, // Port number localAddress: '192.168.1.100', // Local interface family: 4, // IP version (4 or 6) timeout: 5000 // Connection timeout (milliseconds)});
Socket Object
It is an abstraction of TCP connections, with the characteristics of Duplex Stream, which is both readable and writable.
Create Socket
In addition to automatic server creation, you can also create it manually:
const socket = new (); (3000, 'localhost', () => { ('Connected successfully'); });
Socket properties
-
: Remote IP address
-
: Remote port
-
: Local IP address
-
: Local port
-
: Number of bytes received
-
: Number of bytes sent
('connect', () => { (`Connect to ${}:${}`); (`Local port: ${}`); });
Socket method
-
(data[, encoding][, callback])
: Send data -
([data][, encoding][, callback])
: End the connection -
([error])
: Forced to close the connection -
()
: Pause data reading -
()
: Recover data reading -
([enable][, initialDelay])
: Set keepalive -
([noDelay])
: Disable the Nagle algorithm
Event handling
Server Events
('listening', () => { const address = (); (`Server listening ${}:${}`); }); ('error', (err) => { if ( === 'EADDRINUSE') { ('The port has been occupied'); } });
Socket Events
-
connect
: Triggered when a connection is successfully established -
data
: Triggered when data is received -
end
: Triggered when the other party ends sending data -
timeout
: Triggered when the connection timeout -
error
: Triggered when an error occurs -
close
: Triggered when the connection is completely closed
('data', (data) => { (`Received data: ${()}`); }); ('timeout', () => { ('Connection timed out'); (); }); ('close', (hadError) => { (`Connection closes${hadError ? ', an error occurred' : ''}`); });
Data transmission
Send data
// Send string('Hello', 'utf8'); // Send Bufferconst buffer = ([0x68, 0x65, 0x6c, 0x6c, 0x6f]); (buffer); // Use callback to confirm that the data has been sent('World', () => { ('Data sent'); });
Receive data
let chunks = []; ('data', (chunk) => { (chunk); }); ('end', () => { const data = (chunks).toString(); (`Complete data: ${data}`); });
Process binary data
('data', (chunk) => { // Assume that the first two bytes represent the message length const messageLength = chunk.readUInt16BE(0); const message = (2, 2 + messageLength); (`Message content: ${()}`); });
Advanced Features
IPC (Inter-process communication)
In addition to TCP communication,net
The module also supports inter-process communication through Unix domain sockets or named pipes:
// serverconst server = ().listen('/tmp/'); // Clientconst client = ({ path: '/tmp/' });
Multi-connection management
In practical applications, servers usually need to manage multiple connections:
const connections = new Map(); ('connection', (socket) => { const id = `${}:${}`; (id, socket); ('close', () => { (id); (`Client ${id} Disconnected,Current connection number: ${}`); }); }); // Broadcast messages to all clientsfunction broadcast(message) { for (const socket of ()) { (message); } }
Reconnect mechanism
Example of client disconnection:
function createClient() { const client = ({ port: 3000 }); ('error', (err) => { ('Connection error:', err); }); ('close', () => { ('Connection is closed, try reconnecting...'); setTimeout(() => { createClient(); }, 3000); // Reconnect after 3 seconds }); return client; } const client = createClient();
Practical application cases
Simple chat server
const net = require('net'); const clients = []; const server = ((socket) => { // Assign a nickname to the new connection = `user${ + 1}`; // Broadcast new user connection message const message = `${} Joined in the chat room`; broadcast(message, socket); // Add to client list (socket); // Welcome message (`Welcome to the chat room,${}!\n`); // Receive message ('data', (data) => { broadcast(`${}: ${data}`, socket); }); // Disconnect ('end', () => { ((socket), 1); broadcast(`${} Leaving the chat room`, socket); }); // Handle errors ('error', (err) => { (`${} An error occurred:`, err); }); }); // Broadcast messages to all clientsfunction broadcast(message, sender) { ((client) => { // Not sent to the sender of the message if (client !== sender) { (message); } }); (message); } (3000, () => { ('The chat server has been started, listening port 3000'); });
Simple HTTP server
usenet
Module implementation basic HTTP server:
const net = require('net'); const server = ((socket) => { ('data', (data) => { const request = (); ('Received the request:', request); // Simple HTTP response const response = [ 'HTTP/1.1 200 OK', 'Content-Type: text/html', 'Connection: close', '', '<html><body><h1>Hello from net module</h1></body></html>' ].join('\r\n'); (response); (); }); ('error', (err) => { ('Socket Error:', err); }); }); (8080, () => { ('The HTTP server runs at http://localhost:8080/'); });
Performance optimization
Using Buffer Pools
For high-performance applications, you can use the Buffer pool to avoid frequent creation of new Buffers:
const bufferPool = (1024 * 100); // 100KB poollet offset = 0; function allocateBuffer(size) { if (offset + size > ) { offset = 0; // Reset the offset } const buffer = (offset, offset + size); offset += size; return buffer; } // Send data using pre-allocated bufferconst dataToSend = "Hello"; const buffer = allocateBuffer(); (dataToSend); (buffer);
Avoid sending packets
Merging small packets can improve network efficiency:
const queue = []; let isFlushing = false; function queueData(socket, data) { (data); if (!isFlushing) { isFlushing = true; (flushQueue, socket); } } function flushQueue(socket) { if ( > 0) { const data = (queue); = 0; (data); } isFlushing = false; }
Adjust Socket parameters
Optimize Socket settings for different scenarios:
// Low-latency application (disable Nagle algorithm)(true); // Long connection application(true, 60000); // 60 seconds // Set timeout(30000); // 30 seconds('timeout', () => { ('Connection timed out'); (); });
FAQ
Q: How to deal with EADDRINUSE errors?
A: This error indicates that the port has been occupied and can be handled in the following ways:
('error', (err) => { if ( === 'EADDRINUSE') { ('The port has been occupied, try other ports...'); (); (port + 1); } });
Q: How to implement the heartbeat mechanism?
A: Ensure the connection is active by sending heartbeat packets regularly:
// Server heartbeat detectionconst clients = new Map(); ('connection', (socket) => { const id = `${}:${}`; (id, { socket, lastHeartbeat: () }); ('data', (data) => { if (() === 'PING') { (id).lastHeartbeat = (); ('PONG'); } }); }); // Check the client's heartbeat every 10 secondssetInterval(() => { const now = (); for (const [id, client] of ()) { // If the client does not have a heartbeat for 30 seconds, disconnect if (now - > 30000) { (`Client ${id} Heartbeat timeout,Disconnect`); (); (id); } } }, 10000); // Client heartbeatconst client = ({ port: 3000 }); setInterval(() => { ('PING'); }, 10000);
Q: How to deal with large amounts of data transmission?
A: Use flow control and data chunking:
const fs = require('fs'); // Send large filesfunction sendLargeFile(socket, filePath) { const fileStream = (filePath); ('data', (chunk) => { // Check whether the buffer is full const canContinue = (chunk); if (!canContinue) { // If the buffer is full, pause reading (); // When the buffer is cleared, resume reading ('drain', () => { (); }); } }); ('end', () => { ('File sending is complete'); }); }
This is the end of this article about the use examples of the net module. For more related contents of the net module, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!