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

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application
