Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the net module in Nodejs

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of how to use the net module in Nodejs, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this article on how to use the net module in Nodejs. Let's take a look at it.

1. OSI seven-layer protocol model

If you want to learn the communication module, you have to understand the network communication model, and if you want to remember the network communication model, you have to do it in practice to assist memory. This is the focus of the interview. This piece of content is a lot, want to follow in-depth understanding, but also said that the need for systematic learning. This is just a simple mention.

Send this old picture:

For our front end, we need to keep in mind that the system results of the TCP/IP protocol suite are acceptable.

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

Transport layer: TCP/ UDP

Internet layer: IP,ICMP (an adjunct protocol to the IP layer)

Data link layer: PPP, SLIP

Physical layer: there are twisted pair, coaxial cable, optical fiber and other transmission modes in the network, following the ISO2110 specification.

From ICMP, which is attached to IP protocol, we can see that there is no need to be too competitive with the layering of network protocols. ICMP obviously needs to be based on the IP protocol, but it is also planned as the network layer. In our correct understanding of the OSI model, I think it is more meaningful to use the OSI model to analyze the problem than to layer the protocol.

The TCP/IP protocol suite does not only refer to TCP and IP protocols, but because these two protocols are too out of the circle, so we use TCP/IP to refer to the Internet-related protocols together. Another term is the general term for the family of protocols used in the use of the TCP/IP protocol.

The transport streams of the client and server are as follows

If the role becomes the sender and receiver, the transport stream is shown below:

It can be seen that in the process of transmission, the required first information will be added without going through a layer of protocol from the sender. Check the gate layer by layer and increase the code layer by layer. Then when it comes to the receiving end, it goes instead, peeling off the corresponding head after each layer. Just wait until you finally get the HTTP data.

The picture above is from "graphic HTTP"

The above is a general model of network protocol.

Question: why does the name of the network layer become the internetwork layer after the results of the OSI system are merged into the TCP/IP layer 5 protocol in the book and in many places?

2. TCP connection

First handshake: the client sends the SYN flag bit (serial number is J) to the server and enters the SYN_SENT state (waiting for the server to confirm)

Second handshake: the server receives the SYN J from the client, and the server acknowledges that the packet has been received and sends the ACK flag bit (sequence number is J + 1) and SYN flag bit (sequence number is K), then enters the SYN_REVD state (requests to be accepted and waits for client confirmation status)

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

Both J and K are to establish who is requesting it. The structure of SYN is no different from that of ACK, except that the objects sent are different.

3. Net module

The net module is the specific implementation of the above TCP connection.

First of all, learning API is still recommended to go directly to the official documentation. The content of the Chinese document will not be the latest version.

When you are studying, try to read English documents when you have time. I persisted on this point for half a year. I can't watch it from the beginning, until now I can resist the discomfort. The progress is obvious in half a year. And this discomfort is a good thing, indicating that this is not your comfort zone, after all, the courage to cross your own comfort zone is the source of progress.

Next, let's get down to business. Since we want to learn to communicate, we need two objects to simulate the client and the server. Establish two files, client.js and service.js, respectively. Create from the command line:

Touch client.js & & touch service.js3.1 service.js part

Introduce the net module, put the server into the LISTENT state, and configure the port number and HOST address (manually skip the DNS parsing process), waiting for the client to call

Const net = require ("net"); const post = 3306 Taiwan Const host = "127.0.0.1"; const server = net.createServer (); server.listen (post, host)

At this point, the server corresponds to the LISTEN status of the server in the TCP connection.

Then listen for necessary events, that is, hooks provided by server. (belongs to event related knowledge)

Server.on ("listening", () = > {console.log ("the server is ready to connect"); server.on ("connection", (socket) = > {console.log ("there is a client visiting"); server.on ("close", () = > {console.log ("server is down");}); server.on ("error", (error) = > {console.log ("server error:", error) / / error has an error message})

The above string of code involves

Listening: events that start after listening on the port

Connection: triggers an event when a client visits

Close: server shutdown trigger

Error: triggered by a server error

What we need to note about close is that backstage eldest brother is usually direct.

Pskill-9 pid

By killing the thread.

In connection dogs, the parameter is named socket. It is translated into nested words in Chinese and encapsulated into stream (stream) by node. It can be interpreted as the data sent by the client. This is that the data itself has a method. I deal with socket in connection

Server.on ("connection", (socket) = > {console.log ("client visits"); socket.on ("data", (data) = > {console.log (data); / / data sent by the client});})

Stream will be introduced in future articles.

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

Socket.write ("I have received your server, client")

At this point, if the client has completed the acceptance of the data, and then closed the connection. We can also hear it through the socket.on ('close') hook:

Socket.on ("close", () = > {console.log ("client shuts down the stream at the other end");})

A summary of socket events is placed in client.js. At this point, all the contents of service.js are as follows:

Const net = require ("net"); const post = 3306 Boston Const host = "127.0.0.1"; const server = net.createServer (); server.listen (post, host); server.on ("listening", () = > {console.log ("the server is ready to connect";}); server.on ("connection", (socket) = > {console.log ("client visiting") Socket.on ("data", (data) = > {console.log (data); / / data socket.write sent by the client ("I have received your server, client"); socket.on ("close", () = > {console.log ("the client shuts down the stream from the other end"); server.close () / / the client no longer wants data, so let's shut down the server});}); server.on ("close", () = > {console.log ("server is down");}); server.on ("error", (error) = > {console.log ("server error:", error); / / error has an error message}); 3.2 client.js section

The client side is much simpler.

Const net = require ("net"); const post = 3306 Boston Const host = "127.0.0.1"; const socket = net.connect (post, host); socket.on ("connect", () = > {console.log ("already connected to the server";}); socket.write ("server, I'm here"); socket.on ("data", (data) = > {console.log (data.toString ()); socket.end ();})) Socket.on ("close", () = > {console.log ("connection closed");})

A summary of socket's events

Connect: successful and server connection trigger

Data: receives the parameters sent by the server

End: can be triggered after the data has been received

Close: socket shutdown trigger

The service.js and client.js frameworks have been written, and those who open two terminals one after another run them:

Node service.jsnode client.js

Check the printed results by yourself.

The framework of the entire TCP connection is almost complete. Of course, the actual production is much more than that. Also deal with sticking, unpacking / sealing, heartbeat and so on.

This is the end of the article on "how to use net modules in Nodejs". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to use the net module in Nodejs". If you want to learn more knowledge, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report