Home  >  Article  >  Web Front-end  >  Teach you step by step how to use Node.js for TCP network communication (Practice)

Teach you step by step how to use Node.js for TCP network communication (Practice)

青灯夜游
青灯夜游forward
2021-09-24 10:28:047744browse

How to use Node.js for TCP network communication? The following article will help you understand how to use Node.js for TCP network communication. I hope it will be helpful to you!

Teach you step by step how to use Node.js for TCP network communication (Practice)

Abstract: The network is the basis of communication and interconnection. Node.js provides modules such as net, http, and dgram, which are used to implement TCP, HTTP, and UDP respectively. Communication, this article mainly records the practice of TCP communication using Node.js. [Recommended learning: "nodejs Tutorial"]

1. Build a TCP server

##1.1. Use Node.js creates 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. Easily create a TCP server, the syntax format is as follows:

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

1.2. Listen for client connections

Just use the listen method of the TCP server Start listening for client connections. 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 that listen is executed on the console The callback function of the method is as shown in the figure:

Teach you step by step how to use Node.js for TCP network communication (Practice)

You can use the corresponding TCP client or debugging tool to connect to the created TCP server. For example, if you want to use Windows Telnet, 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 "New client access", indicating that the callback function of the createServer method has been Execute, indicating that you have successfully connected to the created TCP server.

Teach you step by step how to use Node.js for TCP network communication (Practice)

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

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

Except In addition to the listening event, 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, Check the address the server listens on

After creating a TCP server, you can use the server.address() method to check the address the TCP server listens on and return a JSON object because of this The method returns the address information monitored by the TCP server, so this method should be called when the server.listen() method is called or the callback function in the event listening is bound. The attributes of this object are:

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

The code is as follows:

//引入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 running result is as shown:

Teach you step by step how to use Node.js for TCP network communication (Practice)

##1.4 ,The number of clients connected to the serverAfter creating a TCP server, you can obtain the number of clients connected to the TCP server through the server.getConnections() method. This method is an asynchronous method. The callback function has two parameters:

第一个参数为error对象。
第二个参数为连接TCP服务器的客户端数量。

In addition to getting the number of connections, you can also set the maximum number of connections for the TCP server by setting the maxConnections attribute 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 for 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, new clients cannot connect to the server, as shown in the figure:

Teach you step by step how to use Node.js for TCP network communication (Practice)

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 that the server listens to). This object also has an address() method. Used to obtain the address bound to the TCP server, it also returns an object containing the port, family, and address attributes. 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:

Teach you step by step how to use Node.js for TCP network communication (Practice) In addition to data events, the socket object also has connect, end, error, timeout and other events.

1.6. Send data to the client

调用socket.write()可以使TCP服务器发送数据,这个方法只有一个必需参数,就是需要发送的数据;第二个参数为编码格式,可选。同时,可以为这个方法设置一个回调函数。当有用户连接TCP服务器的时候,将发送数据给客户端,代码如下:

//引入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("服务正在监听中。。。")
});

测试结果如下:

Teach you step by step how to use Node.js for TCP network communication (Practice)

在上面这段代码中还用到了socket对象的bytesWritten和bytesRead属性,这两个属性分别代表着发送数据的字节数和接收数据的字节数。除了上面这两个属性外,socket对象还有以下属性:

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

2、构建TCP客户端

Node.js在创建一个TCP客户端的时候同样使用的是net(网络)模块。

2.1、使用Node.js创建TCP客户端

为了使用Node.js创建TCP客户端,首先要调用require(‘net’)来加载net模块。创建一个TCP客户端只需要创建一个连接TCP客户端的socket对象即可:

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

创建一个socket对象的时候可以传入一个json对象。这个对象有以下属性:

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

2.2、连接TCP服务器

创建了一个socket对象后,调用socket对象的connect()方法就可以连接一个TCP服务器,代码如下:

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

连接成功如下图所示:

Teach you step by step how to use Node.js for TCP network communication (Practice)

2.3、获取从TCP服务器发送的数据

socket对象有data、error、close、end等事件,因可以通过监听data事件来获取从TCP服务器发送的数据,代码如下:

//引入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());
});

先启动TCP服务端,再运行上面客户端,可以发现命令行中已经输出了来自服务端的数据,说明此时已经实现了服务端和客户端之间的通信:

Teach you step by step how to use Node.js for TCP network communication (Practice)

2.4、向TCP服务器发送数据

因为TCP客户端是一个socket对象,所以可以使用以下代码来向TCP服务器发送数据:

//引入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("客户端发送数据结束")
});

客户端控制台输出:

Teach you step by step how to use Node.js for TCP network communication (Practice)

服务端控制台输出:

Teach you step by step how to use Node.js for TCP network communication (Practice)

至此使用Node.js进行TCP网络通信完成,如有不对的地方欢迎指正。

原文地址:https://bbs.huaweicloud.com/blogs/300544?utm_source=juejin&utm_medium=bbs-ex&utm_campaign=other&utm_content=content

作者:lwq1228

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Teach you step by step how to use Node.js for TCP network communication (Practice). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:华为云社区. If there is any infringement, please contact admin@php.cn delete