


Teach you step by step how to use Node.js for TCP network communication (Practice)
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!
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:
telnet localhost 8001After 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.
//设置监听端口 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:
##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:
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:
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服务器的时候,将发送数据给客户端,代码如下: 测试结果如下: 在上面这段代码中还用到了socket对象的bytesWritten和bytesRead属性,这两个属性分别代表着发送数据的字节数和接收数据的字节数。除了上面这两个属性外,socket对象还有以下属性: Node.js在创建一个TCP客户端的时候同样使用的是net(网络)模块。 2.1、使用Node.js创建TCP客户端 为了使用Node.js创建TCP客户端,首先要调用require(‘net’)来加载net模块。创建一个TCP客户端只需要创建一个连接TCP客户端的socket对象即可: 创建一个socket对象的时候可以传入一个json对象。这个对象有以下属性: 2.2、连接TCP服务器 创建了一个socket对象后,调用socket对象的connect()方法就可以连接一个TCP服务器,代码如下: 连接成功如下图所示: 2.3、获取从TCP服务器发送的数据 socket对象有data、error、close、end等事件,因可以通过监听data事件来获取从TCP服务器发送的数据,代码如下: 先启动TCP服务端,再运行上面客户端,可以发现命令行中已经输出了来自服务端的数据,说明此时已经实现了服务端和客户端之间的通信: 2.4、向TCP服务器发送数据 因为TCP客户端是一个socket对象,所以可以使用以下代码来向TCP服务器发送数据: 客户端控制台输出: 服务端控制台输出: 至此使用Node.js进行TCP网络通信完成,如有不对的地方欢迎指正。 原文地址:https://bbs.huaweicloud.com/blogs/300544?utm_source=juejin&utm_medium=bbs-ex&utm_campaign=other&utm_content=content 作者:lwq1228 更多编程相关知识,请访问:编程视频!!//引入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("服务正在监听中。。。")
});
socket.localPort:本地端口的地址;
socket.localAddress:本地IP地址;
socket.remotePort:进程端口地址;
socket.remoteFamily:进程IP协议族;
socket.remoteAddress:进程IP地址。
2、构建TCP客户端
//引入net模块
const net = require('net');
//创建TCP客户端
const client = new net.Socket();
fd:指定一个存在的文件描述符,默认值为null;
readable:是否允许在这个socket上读,默认值为false;
writeable:是否允许在这个socket上写,默认值为false;
allowHalfOpen:该属性为false时,TCP服务器接收到客户端发送的一个FIN包后,将会回发一个FIN包;该属性为true时,TCP服务器接收到客户端发送的一个FIN包后不会回发FIN包。
//引入net模块
const net = require('net');
//创建TCP客户端
const client = new net.Socket();
//设置连接的服务器
client.connect(8001, '127.0.0.1', function () {
console.log("连接服务器成功");
});
//引入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());
});
//引入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("客户端发送数据结束")
});
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!

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Notepad++7.3.1
Easy-to-use and free code editor
