This article will take you through the net module in Node, I hope it will be helpful to you!
This is the first article in the Nodejs series. When I watched tutorials before, many of them started from IO, buffer, path, event, Let’s start with the fs, process, and node event loop mechanisms. These are indeed the development dependencies that node development mainly depends on. But I am more anxious. From learning about node, it means that node can do the backend, but the first half of these courses are To talk about the capabilities it has, it is the introduction of the module on how to communicate with the client at the end.
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. It is comfortable. Even if the knowledge points of event module and fs module are involved in the process, you can put it aside temporarily and only understand how the net
module implements communication as a whole.
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 for the interview Key points. There is a lot of content in this section. I want to understand it in depth, and it also requires systematic study. Here is just a brief mention.
Send this old picture:
For our front-end, we need to remember the system results of the TCP/IP protocol cluster.
ICMP protocol that is attached to the IP protocol, we can know that there is no need for layering of network protocols. Too competitive.
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 problems rather than using it. The so-called layering of protocols is more meaningful.
TCP/IP protocol cluster does not just refer to TCP and IP protocols, but because these two protocols are too out of the circle, TCP/IP is used. IP collectively refers to the collection of protocols related to the Internet. There is another way of saying it, the collective name for the protocol family used in the process of using the TCP/IP protocol.And the client and server The transmission flow is as follows If the roles become
sender and
recipient, the transmission flow is as follows:
The above picture is from "Illustrated HTTP"The above is the general network protocol model.Doubt: Why in books and many places after merging the OSI system results into the TCP/IP five-layer protocol, the name of the network layer will become the Internet layer What?
J and K are both for Establish who is requesting. There is no difference in the structure of SYN and ACK, but the objects sent are different.
net module is the specific implementation of the above TCP connection.
First of all, to learn the API, it is still recommended to go directly to the official documentation. The Chinese documentation content will not be the latest version
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
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 client.js
and service.js
respectively. Create them through the command line:
touch client.js && touch service.js
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 triggerFor 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 有错误的信息 });
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 serverdata
: Receive parameters sent from the serverend
: Trigger after data reception is completedclose
: Trigger when socket is closed#service.js and
client.js frameworks have been written. Open two terminals and run them:
node service.js node client.js
This article is reproduced from: https://juejin.cn/post/7084618854801866765Author: I am Little OrangeFor more node-related knowledge, please visit:
nodejs tutorial!
The above is the detailed content of An in-depth analysis of the net module in Nodejs. For more information, please follow other related articles on the PHP Chinese website!