search
HomeWeb Front-endJS TutorialAn article to talk about the net module in Node

An article to talk about the net module in Node

Feb 09, 2023 pm 08:00 PM
node.jsnodenet module

The net module is provided in Node.js, which provides encapsulation and support for TCP and Socket. This article will introduce you to the net module in Node. I hope it will be helpful to you!

An article to talk about the net module in Node

When I watched tutorials before, many of them started with the IO, buffer, path, event, fs, process, and node event loop mechanisms. These are indeed the main development dependencies that node development relies on. But I am quite anxious. From the time I learned about node, it means that node can do the backend. However, the first half of these courses are all about the capabilities it has, that is, how to communicate with customers in the end. Introduction to the module of client communication.

I feel very uncomfortable, so when I write my own summary, I must write the module that communicates between the server and the client first to feel comfortable. Even if the event module and fs module are involved in the process You can put aside the knowledge points for the time being and just understand how the net module implements communication as a whole.

1. OSI seven-layer protocol model

If you want to learn the communication module, you have to understand the network communication model. If you want to remember the network communication model, you have to practice it to assist memory. This is the focus of the interview. There is a lot of content in this area, and I want to have a deeper understanding. , also said that systematic learning is required. Here is just a brief mention. [Recommended related tutorials: nodejs video tutorial, Programming teaching]

Send this old picture:

An article to talk about the net module in Node

##For our front-end, we need to remember the system results of the TCP/IP protocol cluster.

  • Application layer: http(80 port), FTP(21), SMTP( Send mail), POP (receive mail), DNS

  • Transport layer: TCP/ UDP

  • Internet layer: IP, ICMP (is IP Layer accessory protocols)

  • Data link layer: PPP, SLIP

  • Physical layer: The network has twisted pair, coaxial cable, Optical fiber and other transmission methods follow the ISO2110 specification

From

ICMP, a protocol that is attached to the IP protocol, we can know that there is no need to be too strenuous about the layering of network protocols. ICMP Obviously needs the IP protocol as the basis, but it is also planned as the network layer. Our correct understanding of the OSI model, I think, should be to use the OSI model to analyze the problem rather than to use the so-called protocol. The layering is more meaningful.

The TCP/IP protocol cluster does not just refer to the TCP and IP protocols, but because these two protocols are too out of the circle, TCP/IP is used to collectively refer to the Internet. Related protocols are gathered together. Another way to say it is, the collective name of the protocol family used in the process of using the TCP/IP protocol.

The transmission flow of the client and server is as follows

An article to talk about the net module in Node##If the roles become

sender

and recipient, the transmission flow is as follows:

An article to talk about the net module in Node It can be seen that during the transmission process, starting from the sending end, the required header information will be added without passing through a layer of protocol. Layers of checks, layer by layer of coding. Then when it comes to the receiving end, Instead, the corresponding header is peeled off after each layer. Just wait until the HTTP data is finally obtained.

The above picture is from "Illustrated HTTP"

above It is the general network protocol model.

Doubt: Why does the name of the network layer become the Internet layer after merging the OSI system results into the TCP/IP five-layer protocol in books and many places?

2. TCP connection

An article to talk about the net module in Node#First handshake: The client sends the SYN flag (sequence number is J) to the server, and Enter the SYN_SENT state (waiting for the server to confirm the state)

Second handshake: The server receives the SYN J from the client, the server will confirm that the data packet has been received and send the ACK flag (the sequence number is J 1) and the SYN flag bit (the sequence number is K), and then enters the SYN_REVD state (request acceptance and waiting for client confirmation state)

The third handshake: After the client enters the connection establishment state, it sends ACK to the server Flag bit (K 1), confirms that the client has received the established connection. After the server receives the ACK flag, the server enters the connection established state.

J and K are both used to establish who is in the connection. Request. There is no difference in the structure of SYN and ACK, but the objects sent are different.

3. net module

net module

It is the specific implementation of the above TCP connection.<p>First of all, to learn the API, it is still recommended to go directly to the <a href="https://link.juejin.cn?target=https%3A%2F%2Fnodejs.org%2Fdist%2Flatest-v17.x%2Fdocs%2Fapi%2Fnet.html" target="_blank" rel="nofollow noopener noreferrer" title="https://nodejs.org/dist/latest-v17.x/docs/api/net.html" ref="nofollow noopener noreferrer">official documentation</a>. The <a href="https://link.juejin.cn?target=http%3A%2F%2Fnodejs.cn%2Fapi%2Findex.html" target="_blank" rel="nofollow noopener noreferrer" title="http://nodejs.cn/api/index.html" ref="nofollow noopener noreferrer">Chinese documentation</a> content will not be the latest version</p> <blockquote><p>When learning, Whenever I have time to read English documents, I try to read English documents. I have insisted on this for half a year. I couldn't stand it at the beginning, but now I can endure the discomfort and read it. The progress has been obvious in half a year. And this kind of Discomfort is a good thing, it means that this is not your comfort zone. After all, the courage to cross your comfort zone is the source of progress</p></blockquote> <p> Next, let’s get to the point. Since you want to learn communication, then We need two objects to simulate the client and server. Create two files <code>client.js and service.js respectively. Create them through the command line:

touch client.js && touch service.js

3.1 service.js part

Introduces the net module, and puts the server into the LISTENT state, and configures the port number and HOST address (manually Skip the DNS resolution process) and wait for the client's call

const net = require("net");
const post = 3306;
const host = "127.0.0.1";

const server = net.createServer();
server.listen(post, host);

At this time, the server corresponds to the TCP connection serverLISTEN status.

Then monitor some necessary events, and It is the hook provided by the server. (Belongs to event-related knowledge)

server.on("listening", () => {
  console.log("服务器已经可以连接啦");
});

server.on("connection", (socket) => {
  console.log("有客户端来访咯");
});

server.on("close", () => {
  console.log("服务器关闭了");
});

server.on("error", (error) => {
  console.log("服务器出错啦: ", error); // error 有错误的信息
});

The above string of codes involves,

  • listening: Events triggered after listening to the port
  • connection: The event is triggered when a client visits
  • close: The event is triggered when the server is closed
  • error: Server error trigger

For close we need to note that the background brother usually directly

ps
kill -9 pid

kills the thread.

In connection Gouzi, the formal parameter is the socket name. Its Chinese translation is a nested word, which is encapsulated into a stream by node. It can be roughly understood as The data sent by the client. This is the data itself has its own method. I process socket in connection

server.on("connection", (socket) => {
  console.log("有客户端来访咯");

  socket.on("data", (data) => {
    console.log(data); // 客户端发送过来的数据
  });
});

stream later The article will introduce it.

Since the server can accept the data sent by the client, it can naturally reply to the client. Write in socket.on (of course It can also be written outside):

socket.write("我已经收到你的服务器了哦,客户端");

At this time, if the client has completed accepting the data and then closed the connection. We can also pass socket.on('close') The hook listens to:

socket.on("close", () => {
  console.log("客户端把另外一头的流给关了");
});

The summary of socket events is put into client.js. At this time, all the contents of service.js are as follows:

const net = require("net");
const post = 3306;
const host = "127.0.0.1";

const server = net.createServer();
server.listen(post, host);

server.on("listening", () => {
  console.log("服务器已经可以连接啦");
});

server.on("connection", (socket) => {
  console.log("有客户端来访咯");

  socket.on("data", (data) => {
    console.log(data); // 客户端发送过来的数据

    socket.write("我已经收到你的服务器了哦,客户端");
  });

  socket.on("close", () => {
    console.log("客户端把另外一头的流给关了");
    server.close(); // 客户端已经不要数据了,那么我们就把服务器给关闭了吧
  });
});

server.on("close", () => {
  console.log("服务器关闭了");
});

server.on("error", (error) => {
  console.log("服务器出错啦: ", error); // error 有错误的信息
});

3.2 client.js part

The client side is much simpler.

const net = require("net");
const post = 3306;
const host = "127.0.0.1";

const socket = net.connect(post, host);

socket.on("connect", () => {
  console.log("已经连接到服务器了哦");
});

socket.write("服务器, 我来了");
socket.on("data", (data) => {
  console.log(data.toString());
  socket.end();
});

socket.on("close", () => {
  console.log("连接已关闭了");
});

Summary of events for socket

  • connect: Triggered by successful connection to the server
  • data : Receive parameters sent from the server
  • end: Trigger after data reception is completed
  • close: Trigger when socket is closed
  • ## The

#service.js and client.js frameworks have been written. Open two terminals and run them:

node service.js
node client.js

View the printed results by yourself .

The entire TCP connection framework has been basically completed. Of course, the actual production is far more than that. We also need to deal with sticky packets, unpacking/packaging, heartbeat packets, etc.

This article is reproduced from: https://juejin.cn/post/7084618854801866765

Author: I am Little Orange

For more node-related knowledge, please visit:

nodejs tutorial!

The above is the detailed content of An article to talk about the net module in Node. 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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.