Node
is a network-oriented platform. It is event-driven, non-blocking, single-threaded and has good scalability, making it It is very lightweight and suitable for playing various roles in distributed networks.
Node
provides net
, dgram
, http
, http2
, https
and other modules are used to process TCP
, UDP
, HTTP
, HTTPS
respectively, suitable for both server and client .
Building TCP services
TCP
Services are very common in network applications, and most of the current applications are based on TCP
Built, its full name is Transmission Control Protocol, which belongs to the transport layer protocol in the OSI
model. Many application layer protocols are built based on TCP
, and the typical HTTP
, SMTP
, IMAP
and other protocols. I won’t talk about TCP
related knowledge points here. If you are interested, you can follow my Computer Network column to learn.
Create TCP server
After basically understanding the working principle of TCP
, we can start to create a TCP
The server side accepts network requests. The net
module provides an asynchronous network API
for creating TCP# based on
stream ## or
IPC server and client. [Related tutorial recommendations:
nodejs video tutorial, Programming teaching]
server.js file The following code is as follows:
import net from "net"; const server = net.createServer((socket) => { socket.on("data", (data) => { console.log("监听到客户端的数据:", data.toString()); }); // 监听客户端断开连接事件 socket.on("end", () => { console.log("客户端断开连接"); }); // 发送数据给客户端 socket.end("over over over\n"); }); // 启动服务 server.listen(3000, () => { console.log("服务创建成功"); });We can create a
TCP server through
net.createServer(listener). The parameter of this function is the link event
The listener for connection.
The service is created successfully and the output is in the terminal.
nodemon .\server.jsEarlier we created a server through
net.createServer, then we use
net.connect to create a client for session, the specific code is as follows As shown:
import net from "net"; const client = net.connect({ port: 3000 }, () => { client.write("今晚出去吃饭,收到请 over\n"); }); // 接收服务端的数据 client.on("data", (data) => { console.log("接收服务端的数据: ", data.toString()); // 断开连接 client.end(); }); // 断开连接 client.on("end", () => { console.log("断开连接"); });We execute two files at this time, as shown below:
client.write() has sent data multiple times, but only the data other than
setTimeout is normal. The continuous data sent in
setTimeout does not seem to be one every time. Instead of returning, they will be randomly merged and returned, and sticky packets will appear here.
TCP There are certain optimization strategies for small data packets in the network:
Negle Algorithm, if only one byte of content is sent at a time without optimization, the network It will be filled with datagrams with only a very small amount of valid data, which will be a great waste of network resources. For this situation, this algorithm requires the data in the buffer to reach a certain amount or a certain time before sending it out, so the small data packet will be sent out by the buffer. Algorithms are combined to optimize the network. Although this optimization enables efficient use of the network, data may be delayed in sending.
Node, since
TCP enables the
Negle algorithm by default, you can call
socket.setNoDelay(true) Remove the
Negle algorithm so that
write() can send data to the network immediately:
##Close
The algorithm is not always effective, because it completes the merging on the server side. TCP
The received data will be stored in its own buffer first, and then the application will be notified to receive it. The application layer will be blocked due to network or other problems. The reason is that if the data cannot be retrieved from the TCP
buffer in time, multiple data blocks will be stored in the TCP buffer, which will cause sticky packets.
In
Node, calling createServer()
is equivalent to calling new Server()
, the specific results are shown in the figure below:
这主要的原因它在 Node
源码中有如下定义,所以调用 createServer()
函数实际上调用的是 new Server()
,具体代码如下图所示:
function createServer(options, connectionListener) { return new Server(options, connectionListener); }
该构造函数的定义主要有如下所示:
function Server(options, connectionListener) { EventEmitter.call(this); // 注册连接到来时执行的回调 if (typeof options === "function") { connectionListener = options; options = {}; this.on("connection", connectionListener); } else if (options == null || typeof options === "object") { options = { ...options }; if (typeof connectionListener === "function") { this.on("connection", connectionListener); } } // 服务器建立的连接数 this._connections = 0; this[async_id_symbol] = -1; this._handle = null; this._usingWorkers = false; this._workers = []; this._unref = false; // 服务器下的所有连接是否允许半连接 this.allowHalfOpen = options.allowHalfOpen || false; // 有连接时是否注册读事件 this.pauseOnConnect = !!options.pauseOnConnect; this.noDelay = Boolean(options.noDelay); // 是否支持keepAlive this.keepAlive = Boolean(options.keepAlive); this.keepAliveInitialDelay = ~~(options.keepAliveInitialDelay / 1000); } ObjectSetPrototypeOf(Server.prototype, EventEmitter.prototype); ObjectSetPrototypeOf(Server, EventEmitter);
listen
它返回的是一个普通的 JavaScript
对象,接着调用 listen
函数监听端口,listen
方法支持多种使用方式主要有以下这几种方法:
- 传入的是一个已经创建的
TCP
服务器,而不是需要创建的一个服务器; - 传进来是一个对象,并且带了
fd
字段; - 创建了一个
TCP
服务器,并启动该服务器,如果传入了host
会对其进行域名解析;
该方法的的主要逻辑有如下代码所示:
Server.prototype.listen = function (...args) { /* 处理入参,根据文档我们知道listen可以接收好几个参数, 假设我们这里是只传了端口号9297 */ var normalized = normalizeArgs(args); // normalized = [{port: 9297}, null]; var options = normalized[0]; var cb = normalized[1]; // 第一次listen的时候会创建,如果非空说明已经listen过 if (this._handle) { throw new errors.Error("ERR_SERVER_ALREADY_LISTEN"); } // listen成功后执行的回调 var hasCallback = cb !== null; if (hasCallback) { // listen成功的回调 this.once("listening", cb); } options = options._handle || options.handle || options; // 第一种情况,传进来的是一个TCP服务器,而不是需要创建一个服务器 if (options instanceof TCP) { this._handle = options; this[async_id_symbol] = this._handle.getAsyncId(); listenIncluster(this, null, -1, -1, backlogFromArgs); return this; } // 第二种,传进来一个对象,并且带了fd if (typeof options.fd === "number" && options.fd >= 0) { listenIncluster(this, null, null, null, backlogFromArgs, options.fd); return this; } // 创建一个tcp服务器 var backlog; if (typeof options.port === "number" || typeof options.port === "string") { backlog = options.backlog || backlogFromArgs; // 第三种 启动一个TCP服务器,传了host则先进行DNS解析 if (options.host) { lookupAndListen( this, options.port | 0, options.host, backlog, options.exclusive ); } else { listenIncluster( this, null, options.port | 0, 4, backlog, undefined, options.exclusive ); } return this; } };
listenInCluster
在每种方式的最后丢回调用 listenIncluster
方法,该方法主要做的事情是区分 master
进程 和 worker
进程,采用不同的处理策略:
-
mastr
进程: 直接调用server._listen
启动监听; -
worker
进程: 使用cluster._getServer
处理传入的server
对象,修改server._handle
再调用了server._listen
启动监听;
构建 UDP 服务
UDP
又称用户数据包协议,与 TCP
一样同属于网络层传输层。UDP
和 TCP
最大的不同是 UDP
不是面向链接的。
创建 <span style="font-size: 18px;">UDP</span>
服务
创建 UDP
套接字十分简单,UDP
套接字一旦创建,既可以作为客户端发送数据,也可以作为服务端接收数据,下面的代码创建了一个 UDP
套接字,具体代码如下所示:
import dgram from "node:dgram"; const server = dgram.createSocket("udp4"); server.on("error", (err) => { console.error(`server error:\n${err.stack}`); server.close(); }); server.on("message", (msg, rinfo) => { console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); }); server.on("listening", () => { const address = server.address(); console.log(`server listening ${address.address}:${address.port}`); }); server.bind(3000);
该套接字将接收所有网课上 3000
端口上的消息,在绑定完成后,将触发 listening
事件,会终端执行,会输出 server listening 0.0.0.0:3000
字段。
接下来我们创建一个客户端和服务端进行对话,具体代码如下所示:
import dgram from "node:dgram"; import { Buffer } from "node:buffer"; const message = Buffer.from("你个叼毛"); const client = dgram.createSocket("udp4"); client.send(message, 0, message.length, 3000, "localhost", () => { client.close(); });
终端的最终输出结果如下图所示
UDP 广播
在 dgram
模块中,可以使用 socket
端口对象的 setBroadcast
方法来进行数据的广播:
socket.setBroadcast(flag);
-
flag
: 当flag
为true
时,UDP
服务器或者客户端可以利用其所用的socket
端口对象的send
方法中的地址修改为广播地址。
服务端的代码定义在 server.js
文件,具体代码如下所示:
import dgram from "dgram"; const server = dgram.createSocket("udp4"); server.on("message", function (msg, rinfo) { console.log( "server got: " + msg + " from " + rinfo.address + ":" + rinfo.port ); }); server.on("listening", function () { var address = server.address(); console.log("server listening " + address.address + ":" + address.port); }); server.bind(3000);
客户端的代码定义在 server.js
文件,具体代码如下定义:
import dgram from "dgram"; import { Buffer } from "buffer"; const socket = dgram.createSocket("udp4"); const params = process.argv.splice(2); socket.bind(function () { socket.setBroadcast(true); }); const message = Buffer.from(...params); socket.send(message, 0, message.length, 3000, "255.255.255.255", () => { socket.close(); });
具体运行效果如下图所示:
更多node相关知识,请访问:nodejs 教程!
The above is the detailed content of A brief analysis of TCP and UDP in Node. For more information, please follow other related articles on the PHP Chinese website!

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
