search
HomeWeb Front-endJS TutorialNodejs study notes NET module_node.js

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"):

Copy code The code is as follows:

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

Copy code The code is as follows:

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

Copy code The code is as follows:

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.createServerCreate 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.connectAs 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.

Copy code The code is as follows:

// 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).

Copy code The code is as follows:

// 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 If(client !== clientList[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

Copy code The code is as follows:

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

Copy code The code is as follows:

function broadcast(message, client) {
var cleanup = []
for(var i=0;i If(client !== clientList[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 clientList.splice(clientList.indexOf(cleanup[i]), 1)
}
}

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

Copy code The code is as follows:

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

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

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

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

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

火了!新的JavaScript运行时:Bun,性能完爆Node火了!新的JavaScript运行时:Bun,性能完爆NodeJul 15, 2022 pm 02:03 PM

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

nodejs中lts是什么意思nodejs中lts是什么意思Jun 29, 2022 pm 03:30 PM

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

聊聊Node.js中的多进程和多线程聊聊Node.js中的多进程和多线程Jul 25, 2022 pm 07:45 PM

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

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

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

深入浅析Nodejs中的net模块深入浅析Nodejs中的net模块Apr 11, 2022 pm 08:40 PM

本篇文章带大家带大家了解一下Nodejs中的net模块,希望对大家有所帮助!

怎么获取Node性能监控指标?获取方法分享怎么获取Node性能监控指标?获取方法分享Apr 19, 2022 pm 09:25 PM

怎么获取Node性能监控指标?本篇文章来和大家聊聊Node性能监控指标获取方法,希望对大家有所帮助!

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot 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.

DVWA

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

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor