Abstract: The network is the foundation of communication interconnection. Node.js provides modules such as net, http, dgram, etc., which are used to implement TCP, HTTP, and UDP communications. This article mainly implements the TCP communication part using Node.js record.

This article is shared from the " article Understanding How to Use Node.js for TCP Network Communication ", author: lwq1228.

1. Build a TCP server

1.1, use Node.js to create a TCP server

In order to use Node.js to create a TCP server, 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. The syntax format is as follows:

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

options是一个对象参数值,有两个布尔类型的属性allowHalfOpen和pauseOnConnect。这两个属性默认都是false;
connectionListener是一个当客户端与服务端建立连接时的回调函数,这个回调函数以socket端口对象作为参数。

1.2, monitor the client's connection

Use the listen method of the TCP server to start monitoring the client's connection. The syntax format is as follows:

server.listen(port[, host][, backlog][, callback]);

port:为需要监听的端口号,参数值为0的时候将随机分配一个端口号;
host:服务器地址;
backlog:连接等待队列的最大长度;
callback:回调函数。

The following code can create a TCP server and listen to port 8001:

//引入net模块
const net = require('net');
//创建TCP服务器
const server = net.createServer(function (socket) {
    console.log('有新的客户端接入');
});
//设置监听端口
server.listen(8001, function () {
    console.log('服务正在监听中。。。')
});

Run this code, you can see the callback function that executed the listen method in the console, as shown in the figure:
image.png

You can use the corresponding TCP client or debugging tool to connect to the created TCP server. For example, to use Telnet on Windows, you can use the following command to connect:

telnet localhost 8001
After the connection is successful, you can see that the console prints the words "There is a new client access", indicating that the callback function of the createServer method has been executed, indicating that it has successfully connected to the created TCP server.
image.png

The server.listen() method actually triggers the listening event under the server, so you can also manually listen for the listening event. The code is as follows:

//设置监听端口
server.listen(8001);
//设置监听时的回调函数
server.on('listening', function () {
    console.log("服务正在监听中。。。")
});

In addition to listening events, the TCP server also supports the following events:

connection:当有新的链接创建时触发,回调函数的参数为socket连接对象。
close:TCP服务器关闭的时候触发,回调函数没有参数。
error:TCP服务器发生错误的时候触发,回调函数的参数为error对象。

The following code creates a TCP server through the net.Server class and adds the above events:

//引入net模块
const net = require('net');
//实例化一个服务器对象
const server = new net.Server();
//监听connection事件
server.on('connection', function (socket) {
    console.log('有新的客户端接入');
});
//设置监听端口
server.listen(8001);
//设置监听时的回调函数
server.on('listening', function () {
    console.log('服务正在监听中。。。');
});
//设置关闭时的回调函数
server.on('close', function () {
    console.log('服务已关闭');
});
//设置出错时的回调函数
server.on('error', function (err) {
    console.log('服务运行异常', err);
});

1.3, view the address monitored by the server

When a TCP server is created, 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 information that the TCP server is listening to, so you should call the server Call this method in the .listen() method or the callback function bound to the event listening. The attributes of this object are:

port:TCP服务器监听的端口号;
family:说明TCP服务器监听的地址是IPv6还是IPv4;
address:TCP服务器监听的地址。

code show as below:

//引入net模块
const net = require('net');
//创建TCP服务器
const server = net.createServer(function (socket) {
    console.log('有新的客户端接入');
});
//设置监听端口
server.listen(8001);
//设置监听时的回调函数
server.on('listening', function () {
    //获取地址信息
    let address = server.address();
    //获取地址详细信息
    console.log("服务器监听的端口是:" + address.port);
    console.log("服务器监听的地址是:" + address.address);
    console.log("服务器监听的地址类型是:" + address.family);
});

The results of the operation are shown in the figure:
image.png

1.4, the number of clients connected to the server

After creating a TCP server, you can get the number of clients connected to this TCP server through the server.getConnections() method. This method is an asynchronous method, the callback function has two parameters:

`The first parameter is the error object.
The second parameter is the number of clients connected to the TCP server. `
In addition to obtaining the number of connections, you can also set the maximum number of connections for this TCP server by setting the maxConnections property of the TCP server. When the number of connections exceeds the maximum number of connections, the server will reject new connections. The following code sets the maximum number of connections of this TCP server to 3.

//引入net模块
const net = require('net');
//创建TCP服务器
const server = net.createServer(function (socket) {
    console.log('有新的客户端接入');
    //设置最大连接数量
    server.maxConnections = 3;
    server.getConnections(function (err, count) {
        console.log("当前连接的客户端个数为:" + count);
    });
});
//设置监听端口
server.listen(8001, function () {
    console.log("服务正在监听中。。。")
});

Run this code and try to connect with multiple clients. It can be found that when the number of client connections exceeds 3, the new client cannot connect to this server, as shown in the figure:
image.png

1.5, get the data sent by the client

The callback function parameter of the createServer method is a net.Socket object (the port object monitored by the server). This object also has an address() method to obtain the address bound to the TCP server. It also returns a port, family, and The object of the address attribute. The stream data sent by the client can be obtained through the socket object. The data event is triggered every time data is received. By listening to this event, the data sent by the client can be obtained in the callback function. The code is as follows:

//引入net模块
const net = require('net');
//创建TCP服务器
const server = net.createServer(function (socket) {
    //监听data事件
    socket.on("data", function (data) {
        //打印数据
        console.log("接收到数据:" + data.toString());
    });
});
//设置监听端口
server.listen(8001, function () {
    console.log("服务正在监听中。。。")
});

The test results are as follows:
image.png

In addition to data events, socket objects also have events such as connect, end, error, and timeout.

1.6, send data to the client

Call socket.write() to make the TCP server send data. This method has only one required parameter, which is the data to be sent; 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, the data will be sent to the client. The code is as follows:

//引入net模块
const net = require('net');
//创建TCP服务器
const server = net.createServer(function (socket) {
    //设置消息内容
    const message = "Hello Client......";
    //发送数据
    socket.write(message, function () {
        const writeSize = socket.bytesWritten;
        console.log("数据发送成功,数据长度为:" + writeSize);
    });

    //监听data事件
    socket.on("data", function (data) {
        const readSize = socket.bytesRead;
        //打印数据
        console.log("接收到数据为:" + data.toString(), ";接收的数据长度为:" + readSize);
    });
});
//设置监听端口
server.listen(8001, function () {
    console.log("服务正在监听中。。。")
});

The test results are as follows:
image.png

In the above code, the bytesWritten and bytesRead attributes of the socket object are also used. These two attributes represent the number of bytes of data sent and the number of bytes of received data, respectively. In addition to the above two attributes, the socket object has the following attributes:

socket.localPort:本地端口的地址;
socket.localAddress:本地IP地址;
socket.remotePort:进程端口地址;
socket.remoteFamily:进程IP协议族;
socket.remoteAddress:进程IP地址。

2. Build a TCP client

Node.js also uses the net (network) module when creating a TCP client.

2.1, use Node.js to create a TCP client

In order to use Node.js to create a TCP client, 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:

//引入net模块
const net = require('net');
//创建TCP客户端
const client = new net.Socket();

When creating a socket object, you can pass in a json object. This object has the following properties:

fd:指定一个存在的文件描述符,默认值为null;
readable:是否允许在这个socket上读,默认值为false;
writeable:是否允许在这个socket上写,默认值为false;
allowHalfOpen:该属性为false时,TCP服务器接收到客户端发送的一个FIN包后,将会回发一个FIN包;该属性为true时,TCP服务器接收到客户端发送的一个FIN包后不会回发FIN包。

2.2, connect to TCP server

After creating a socket object, call the connect() method of the socket object to connect to a TCP server. The code is as follows:

//引入net模块
const net = require('net');
//创建TCP客户端
const client = new net.Socket();
//设置连接的服务器
client.connect(8001, '127.0.0.1', function () {
    console.log("连接服务器成功");
});

The connection is successful as shown in the figure below:
image.png

2.3. Get the data sent from the TCP server

The socket object has events such as data, error, close, end, etc. Because the data sent from the TCP server can be obtained by monitoring the data event, the code is as follows:

//引入net模块
const net = require('net');
//创建TCP客户端
const client = new net.Socket();
//设置连接的服务器
client.connect(8001, '127.0.0.1', function () {
    console.log("连接服务器成功");
});
//监听data事件
client.on("data", function (data) {
    //打印数据
    console.log("接收到数据为:" + data.toString());
});

Start the TCP server first, and then run the above client, you can find that the data from the server has been output in the command line, indicating that the communication between the server and the client has been realized at this time:
image.png

2.4, send data to TCP server

Because the TCP client is a socket object, you can use the following code to send data to the TCP server:

//引入net模块
const net = require('net');
//创建TCP客户端
const client = new net.Socket();
//设置连接的服务器
client.connect(8001, '127.0.0.1', function () {
    console.log("连接服务器成功");
    //给服务端发送数据
    client.write("Hello Server......");
});
//监听data事件
client.on("data", function (data) {
    //打印数据
    console.log("接收到数据为:" + data.toString());
});
//监听end事件
client.on("end", function () {
    console.log("客户端发送数据结束")
});

Client console output:
image.png

Server console output:
image.png

So far, using Node.js for TCP network communication is complete, please correct me if there is something wrong

Click to follow and learn about Huawei Cloud's fresh technology for the first time~


华为云开发者联盟
1.4k 声望1.8k 粉丝

生于云,长于云,让开发者成为决定性力量