Home > Web Front-end > JS Tutorial > Nodejs study notes NET module_node.js

Nodejs study notes NET module_node.js

WBOY
Release: 2016-05-16 16:20:33
Original
1151 people have browsed it

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template