1, opening analysis
Starting today, we will go deep into the specific module study. This article is the third in this series of articles. The first two articles are mainly theoretical. I believe that everyone will learn from the first two articles.
I also have a basic understanding of NodeJS, so it’s fine! ! ! Strike while the iron is hot, let us continue to carry out NodeJS to the end. Without further ado, let’s go directly to today’s topic “Net module”. So how should “Net” be understood?
What is it used for? (Net
The module can be used to create a Socket server or a Socket client. The two most basic modules for NodeJS data communication are Net and Http. The former is based on Tcp encapsulation, and the latter is essentially a Tcp layer, but a comparison has been made. Multiple data encapsulation, we regard it as the presentation layer).
Here is a reference to the source code in NodeJS “http.js”:
It is not difficult to see from the figure that HttpServer inherits the Net class, has related communication capabilities, and does more data encapsulation. We regard it as a more advanced presentation layer.
Extended knowledge (the following is the source code of "inherits"):
exports.inherits = function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
Constructor: {
Value: ctor,
enumerable: false,
writable: true,
Configurable: true
}
});
};
The function is to realize inheritance and reuse.
I just gave a brief overview, which contains some commonly used concepts. Here is a brief introduction to popularize the concepts:
(1), TCP/IP------TPC/IP protocol is a transport layer protocol, which mainly solves how data is transmitted in the network.
(2), Socket------socket is the encapsulation and application of the TCP/IP protocol (program level).
(3), Http------HTTP is an application layer protocol, which mainly solves how to package data.
(4), seven-layer network model------physical layer, data link layer, network layer, transport layer, session layer, presentation layer and application layer.
To summarize: Socket is an encapsulation of the TCP/IP protocol. Socket itself is not a protocol, but a calling interface (API).
This forms some of the most basic function interfaces we know, such as Create, Listen, Connect, Accept, Send, Read and Write, etc.
TCP/IP is just a protocol stack, just like the operating mechanism of the operating system, it must be implemented concretely, and at the same time it must provide an external operation interface
In fact, the TCP of the transport layer is based on the IP protocol of the network layer, and the HTTP protocol of the application layer is based on the TCP protocol of the transport layer. Socket itself is not a protocol. As mentioned above, it is just Provides an interface for TCP or UDP programming.
Two, experience it
Okay, we have the concept, here is an example:
1, create server.js
var net = require('net') ;
var server = net.createServer(function(c) { // Connection listener
console.log("Server connected") ;
c.on("end", function() {
console.log("Server has been disconnected") ;
}) ;
c.write("Hello, Bigbear !rn") ;
c.pipe(c) ;
}) ;
server.listen(8124, function() { // Listening listener
Console.log("Server is bound") ;
}) ;
2, create client.js
var net = require('net') ;
var client = net.connect({
Port: 8124
},function(){ // connect listener
console.log("Client is connected") ;
client.write('Hello,Baby !rn') ;
});
client.on("data", function(data) {
console.log(data.toString()) ;
client.end() ;
});
client.on("end", function(){
console.log("Client disconnected") ;
}) ;
Analyze it:
Server------net.createServer
Create a TCP service. This service is bound (server.listen) on port 8124. After creating the Server, we see a callback function,
When calling the above function, pass in a parameter. This parameter is also a function and accepts socket. This is a pipe constructed by other methods. Its function is for data interaction.
The pipe needs to be established by the Client to greet the Server. If no client accesses the Server at this moment, this socket will not exist.
客户端------net.connect
As the name suggests, it is to connect to the server. The first parameter is the object. Set the port to 8124, which is the port our server listens on. Since the host parameter is not set, the default is localhost (local) .
In Server, the socket is one end of the pipe, while in client, the client itself is one end of the pipe. If multiple clients connect to the Server, the Server will create multiple new sockets, each socket corresponding to a client.
Run result:
3. Case introduction
(1), the following code is just the server outputting a piece of text to the client, completing one-way communication from the server to the client.
// Sever --> Client's one-way communication
var net = require('net');
var chatServer = net.createServer();
chatServer.on('connection', function(client) {
client.write('Hi!n'); // The server outputs information to the client, using the write() method
client.write('Bye!n');
client.end(); // The server ends the session
});
chatServer.listen(9000);
Test with Telnet: telnet127.0.0.1:9000
After executing telnet, connect to the service point, feedback Hi! Bye! characters, and immediately end the server program to terminate the connection.
What if we want the server to receive information from the client?
You can listen to the server.data event and do not terminate the connection (otherwise it will end immediately and be unable to accept messages from the client).
(2), listen to the server.data event and do not terminate the connection (otherwise it will end immediately and be unable to accept messages from the client).
// Based on the former, realize Client --> Sever communication, so that it is two-way communication
var net = require('net');
var chatServer = net.createServer(),
clientList = [];
chatServer.on('connection', function(client) {
// JS can freely add properties to objects. Here we add a custom attribute of name to indicate which client (based on the client’s address and port)
client.name = client.remoteAddress ':' client.remotePort;
client.write('Hi ' client.name '!n');
clientList.push(client);
client.on('data', function(data) {
Broadcast(data, client);//Accept information from the client
});
});
function broadcast(message, client) {
for(var i=0;i
clientList[i].write(client.name " says " message);
}
}
}
chatServer.listen(9000);
Is the above a fully functional code? We said that there is another issue that has not been taken into account: once a client exits, it is still retained in the clientList, which is obviously a null pointer.
(3), handle clientList
chatServer.on('connection', function(client) {
client.name = client.remoteAddress ':' client.remotePort
client.write('Hi ' client.name '!n');
clientList.push(client)
client.on('data', function(data) {
Broadcast(data, client)
})
client.on('end', function() {
ClientList.splice(clientList.indexOf(client), 1); // Delete the specified element in the array.
})
})
NodeTCPAPI has provided us with the end event, which occurs when the client terminates the connection with the server.
(4), optimize broadcast
function broadcast(message, client) {
var cleanup = []
for(var i=0;i
If(clientList[i].writable) { // First check whether sockets are writable
clientList[i].write(client.name " says " message)
} else {
cleanup.push(clientList[i]) // If it is not writable, collect it and destroy it. Before destruction, Socket.destroy() must be used to destroy it using the API method.
clientList[i].destroy()
}
}
} //Remove dead Nodes out of write loop to avoid trashing loop index
for(i=0;i
}
}
Note that once "end" is not triggered, an exception will occur, so optimization work is done.
(5), NetAPI also provides an error event to capture client exceptions
client.on('error', function(e) {
console.log(e);
});
Four, summary
1. Understand the relevant concepts at the beginning
2. Understand the relationship between Http and Net modules
3. Combined with the examples in this article, check out the relevant APIs to practice
4. Communication ideas between socket client and server
5. If you are interested, you can improve the example of the chat room

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

今天跟大家介绍一个最新开源的 javaScript 运行时:Bun.js。比 Node.js 快三倍,新 JavaScript 运行时 Bun 火了!

在nodejs中,lts是长期支持的意思,是“Long Time Support”的缩写;Node有奇数版本和偶数版本两条发布流程线,当一个奇数版本发布后,最近的一个偶数版本会立即进入LTS维护计划,一直持续18个月,在之后会有12个月的延长维护期,lts期间可以支持“bug fix”变更。

大家都知道 Node.js 是单线程的,却不知它也提供了多进(线)程模块来加速处理一些特殊任务,本文便带领大家了解下 Node.js 的多进(线)程,希望对大家有所帮助!

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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.

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

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

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Atom editor mac version download
The most popular open source editor
