Abstract: Network is the basis of communication interconnection, Node.js provides NET, HTTP, DGRAM and other modules, respectively used to achieve TCP, HTTP, UDP communication, this paper mainly use Node.js TCP communication part of the practice record.
This article is shared by Huawei Cloud community “How to Use Node.js for TCP Network communication” by lwq1228.
1. Build the TCP server
1.1. Use Node.js to create a TCP server
To create a TCP server using Node.js, first call require(‘ NET ‘) to load the NET module, and then call the createServer method of the NET module to easily create a TCP server in the following syntax:
Net.createserver ([Options][, connectionListener]) Options is an object parameter value with two Boolean properties allowHalfOpen and pauseOnConnect. Both properties are false by default; ConnectionListener is a callback function that takes a socket port object as a parameter when a client establishes a connection with a server.Copy the code
1.2. Monitor the connection of the client
Use the TCP server’s LISTEN method to start listening for client connections in the following syntax:
server.listen(port[, host][, backlog][, callback]); Port: indicates the port number to be monitored. If the value is 0, a port number is randomly allocated. Host: indicates the address of the server. Backlog: The maximum length of the connection wait queue; Callback: callback function.Copy the code
The following code can create a TCP server and listen on port 8001:
Const net = require('net'); Const server = net.createserver (function (socket) {console.log(' new client connected '); }); Server.listen (8001, function () {console.log(' Service is listening... ')});Copy the code
Running this code, you can see the listen callback on the console, as shown in the figure below:
You can connect to this created TCP server using the appropriate TCP client or debugging tool. For example, to use Telnet on Windows, you can use the following command to connect:
telnet localhost 8001
Copy the code
After the connection is successful, you can see that the console prints “New client connected”, indicating that the callback function of the createServer method has been executed, indicating that the connection to the created TCP server has been successful.
The server.listen() method triggers a listening event on the server, so you can manually listen for a listening event.
// Set the listening port server.listen(8001); Server. on('listening', function () {console.log(" The service is listening... )});Copy the code
In addition to the Listening event, the TCP server supports the following events:
Connection: Triggered when a new connection is created. The callback function takes the socket connection object as an argument. Close: Triggered when the TCP server is shut down. The callback function has no parameters. Error: This function is triggered when a TCP server error occurs. The parameter of the callback function is the error object.Copy the code
The following code creates a TCP Server using the Net. Server class, adding the above events:
Const net = require('net'); // Instantiate a server object const server = new net.server (); // Listen for connection event server.on('connection', function (socket) {console.log(' new client connected '); }); // Set the listening port server.listen(8001); Server. on('listening', function () {console.log(' service is listening... '); }); Server.on ('close', function () {console.log(' service is closed '); }); Server. on('error', function (err) {console.log(' error', err); });Copy the code
1.3. Check the IP address monitored by the server
When you create a TCP server, you can use the server.address() method to view the address that the TCP server is listening to and return a JSON object, because this method returns the address that the TCP server is listening to. This method should be called either from the server.listen() method or from a callback bound to event listening. The attributes of this object are:
Port: indicates the port number monitored by the TCP server. Family: indicates whether the TCP server listens to IPv6 or IPv4 addresses. Address: indicates the IP address monitored by the TCP server.Copy the code
The code is as follows:
Const net = require('net'); Const server = net.createserver (function (socket) {console.log(' new client connected '); }); // Set the listening port server.listen(8001); Server.on ('listening', function () {let address = server.address(); Console. log(" The server is listening on port: "+ address.port); Console. log(" The address the server listens to is: "+ address.address); Console. log(" The address type the server listens to is: "+ address.family); });Copy the code
The running results are shown as follows:
1.4. Number of clients connected to the server
Once you have created a TCP server, you can use the server.getConnections() method to get the number of clients connected to the TCP server. This method is asynchronous and the callback takes two arguments:
The first argument is an error object. The second parameter is the number of clients connected to the TCP server.Copy the code
In addition to getting the number of connections, you can also set the maximum number of connections for this TCP server by setting the TCP server’s maxConnections property. When the number of connections exceeds the maximum number, the server rejects new connections. The following code sets the maximum number of connections for this TCP server to 3.
Const net = require('net'); Const server = net.createserver (function (socket) {console.log(' new client connected '); // Set the maximum number of connections server.maxConnections = 3; Server.getconnections (function (err, count) {console.log(" Number of clients currently connected: "+ count); }); }); Server.listen (8001, function () {console.log(" the service is listening... )});Copy the code
Run this code and try to connect with multiple clients. It can be found that when the number of client connections exceeds 3, new clients cannot connect to the server, as shown in the figure below:
1.5. Obtain the data sent by the client
The createServer callback takes a net.socket object (the port on which the server listens), which also has an address() method that gets the TCP server bound address, Return an object with port, family, and address attributes. Each time the data is received, the data event is triggered. By listening to this event, the data sent by the client can be obtained in the callback function. The code is as follows:
Const net = require('net'); Const server = net.createserver (function (socket) {// Monitor the data event socket.on("data", Function (data) {// print data console.log(" received data: "+ data.tostring ()); }); }); Server.listen (8001, function () {console.log(" the service is listening... )});Copy the code
The test results are as follows:
Socket objects have data events as well as connect, End, Error, timeout and other events.
1.6. Send data to the client
A call to socket.write() causes the TCP server to send data. This method has only one required argument, which is the data to send; The second parameter is the encoding format, which is optional. At the same time, you can set a callback function for this method. When a user connects to the TCP server, data is sent to the client with the following code:
Const net = require('net'); // Create TCP server const server = net.createserver (function (socket) {const message = "Hello Client......" ; Write (message, function () {const writeSize = socket.byteswritten; Console. log(" Data sent successfully, data length: "+ writeSize); }); On ("data", function (data) {const readSize = socket.bytesRead; // Prints data console.log(" Received data: "+ data.tostring (),"; The received data length is: "+ readSize); }); }); Server.listen (8001, function () {console.log(" the service is listening... )});Copy the code
The test results are as follows:
The above code also uses the socket object’s bytesWritten and bytesRead properties, which represent the number of bytes sent and the number of bytes received, respectively. In addition to these two properties, socket objects have the following properties:
Socket. localPort: indicates the address of the localPort. Socket. localAddress: indicates the local IP address. Socket. remotePort: process port address; Socket. remoteFamily: process IP protocol family; Socket. remoteAddress: indicates the IP address of a process.Copy the code
2. Build a TCP client
Node.js also uses the NET module to create a TCP client.
2.1. Use Node.js to create a TCP client
To create a TCP client using Node.js, first call require(‘ NET ‘) to load the NET module. To create a TCP client, you only need to create a socket object to connect to the TCP client:
Const net = require('net'); // Create TCP client const client = new net.socket ();Copy the code
When creating a socket object, you can pass in a JSON object. This object has the following properties:
Fd: specifies an existing file descriptor. The default is null. Readable: Whether readable is allowed on this socket. The default value is false. Writeable: whether to allow writing on the socket. The default value is false. AllowHalfOpen: If the value is false, the TCP server sends back a FIN packet after receiving one from the client. If this parameter is set to true, the TCP server does not send back a FIN packet sent by the client.Copy the code
2.2. Connect to the TCP server
After creating a socket object, call the connect() method of the socket object to connect to a TCP server as follows:
Const net = require('net'); // Create TCP client const client = new net.socket (); Client.connect (8001, '127.0.0.1', function () {console.log(" connect to server successfully "); });Copy the code
The connection is successful as shown below:
2.3. Get data sent from the TCP server
Socket objects have events such as data, error, close, and end. You can listen for data events to obtain data sent from the TCP server. The code is as follows:
Const net = require('net'); // Create TCP client const client = new net.socket (); Client.connect (8001, '127.0.0.1', function () {console.log(" connect to server successfully "); }); On ("data", function (data) {// Print data console.log(" received data: "+ data.tostring ())); });Copy the code
After starting the TCP server and running the preceding client, you can find that the command line output data from the server, indicating that the communication between the server and the client has been realized.
2.4. Send data to the TCP server
Since the TCP client is a socket object, you can use the following code to send data to the TCP server:
Const net = require('net'); // Create TCP client const client = new net.socket (); Client.connect (8001, '127.0.0.1', function () {console.log(" connect to server successfully "); // Send data to the Server client.write("Hello Server......") ); }); On ("data", function (data) {// Print data console.log(" received data: "+ data.tostring ())); }); Client. On ("end", function () {console.log(" end")});Copy the code
Client console output:
Server console output:
So far the use of Node.js TCP network communication completed, if there is any wrong place welcome to correct.
Click to follow, the first time to learn about Huawei cloud fresh technology ~