Nodejs Learning Notes of the net module _node.js

Source: Internet
Author: User
Tags require

First, the opening analysis

From today, we have to delve into the specific module learning, this article is the third of the series of articles, the first two are mainly based on theory, I believe that everyone in the first two of the study,

To Nodejs also has a basic understanding, nothing!!! While the iron is hot, let us continue to Nodejs to the end, good nonsense not to say, directly into today's theme "NET Module", then "net" how to understand that?

What does it do with that? ( Net modules can be used to create a socket server or socket client.) Nodejs data communication, the most basic two modules are Net and Http, the former is based on TCP encapsulation, the latter is a TCP layer, but did a lot of data encapsulation, we see as the performance layer.

Here refer to Nodejs "Http.js" in the source code:

It is easy to see from the figure that Httpserver inherits the net class, has the related communication ability, has done the more data encapsulation, we regard as the higher performance layer.

Extended knowledge (The following is the "inherits" source):

Copy Code code 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
}
});
};

function is to implement inheritance reuse.

Just made a brief overview, there are some common concepts, here to do a brief introduction to the concept:

(1), TCP/IP------TPC/IP Protocol is a Transport layer protocol, which mainly solves the data transmission in the network.

(2), socket------Socket is the TCP/IP protocol encapsulation and application (program level).

(3), HTTP------HTTP is the application layer protocol, which mainly solves how to wrap the data.

(4), the network seven-layer model------Physical layer, Data link layer, network layer, transport layer, Session layer, presentation layer and application layer.

To sum up: The socket is the TCP/IP protocol encapsulation, the socket itself is not a protocol, but a call interface (API).

This creates some of the most basic function interfaces we know, such as Create, Listen, Connect, Accept, Send, read, write, and so on.

TCP/IP is just a protocol stack, just like the operating system mechanism, it must be implemented, but also to provide external operational 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, and the socket itself is not a protocol, as mentioned above, it only provides an interface for TCP or UDP programming.

Second, experience a

Well, we have the concept, for example:

1, establish server.js

Copy Code code as follows:

var net = require (' net ');
var server = Net.createserver (function (c) {//Connection listener
Console.log ("Server is Connected");
C.on ("End", function () {
Console.log ("Server is Disconnected");
}) ;
C.write ("Hello,bigbear!\r\n");
C.pipe (c);
}) ;
Server.listen (8124, function () {//Listening listener
Console.log ("Server is Bound");
}) ;

2, establish client.js

Copy Code code as follows:

var net = require (' net ');
var client = Net.connect ({
port:8124
},function () {//Connect listener
Console.log ("Client is connected");
Client.write (' Hello,baby!\r\n ');
});
Client.on ("Data", function (data) {
Console.log (Data.tostring ());
Client.end ();
});
Client.on ("End", function () {
Console.log ("Client Disconnected");
}) ;

Analyze:

Server-side------ net.createServer Create a TCP service, this service binding (Server.listen) on the 8124 port, and we see a callback function when we create it.

When you call the above function, you pass in a parameter, which is also a function, and accepts the socket, a pipe constructed by other methods (pipe), whose function is to interact with the data.

Pipe needs to be greeted by the client and the server, and if no clients are accessing the server at the moment, the socket will not exist.

客户端------net.connectAs the name implies, is connected to the server, the first parameter is the object, set the port for 8124, that is, our server listening to the port, because no host parameters are set, the default is localhost (local).

In the Server, the socket is the end of the pipe, and in the client, the client itself is one end of the pipe, and if multiple client connections Server,server a new socket, each socket corresponds to a client.

Run Result:

Third, the introduction of the case

(1), the following code is just the server to the client output a piece of text to complete the service to the client one-way communication.

Copy Code code 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 and uses the Write () method
Client.write (' bye!\n ');
Client.end (); The server ends the session
});
Chatserver.listen (9000);

Telnet test: telnet127.0.0.1:9000

After performing telnet, connect to the service point, feedback hi! bye! And immediately end the server-side program to terminate the connection.

What if we want the server to receive information to the client?

You can listen for server.data events and do not abort the connection (otherwise you will end up not accepting messages from the client).

(2) listens for Server.data events and does not abort the connection (otherwise the message from the client cannot be accepted immediately).

Copy Code code as follows:



On the former basis, the realization of the Client--> Sever communication, so that is two-way communication


var net = require (' net ');


var chatserver = Net.createserver (),


Clientlist = [];


Chatserver.on (' Connection ', function (client) {


JS can add properties to objects freely. Here we add a custom attribute of name, which is used to indicate which client (the client's address + port is based on)


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.length;i+=1) {


if (client!== Clientlist[i]) {


Clientlist[i].write (client.name + "says" + message);


}


}


}


Chatserver.listen (9000);


Is it not a complete function of the code? We say that there is another problem that is not taken into account: once a client exits, it remains in the clientlist, which is clearly a null pointer.

(3), processing clientlist

Copy Code code 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); Deletes the formulation element in the array.
})
})

Nodetcpapi has provided us with the end event, which occurs when the client aborts the connection to the server.

(4) Optimization of broadcast

Copy Code code as follows:

function broadcast (message, client) {
var cleanup = []
for (Var i=0;i<clientlist.length;i+=1) {
if (client!== Clientlist[i]) {
if (clientlist[i].writable) {//Check sockets to write first
Clientlist[i].write (client.name + "says" + message)
} else {
Cleanup.push (Clientlist[i])//If not written, collected and destroyed. Destroy the Socket.destroy () using the API method before destroying it.
Clientlist[i].destroy ()
}
}
//remove dead Nodes out of the write loop to avoid trashing loop index
for (i=0;i<cleanup.length;i+=1) {
Clientlist.splice (Clientlist.indexof (Cleanup[i]), 1)
}
}

Note that once "end" is not triggered, there will be an exception, so the optimization work.

(5) An error event is also provided in the NETAPI to capture the client's exception

Copy Code code as follows:

Client.on (' Error ', function (e) {
Console.log (e);
});

Four, sum up

1, understanding the relevant concepts of the opening

2, understanding the relationship between HTTP and net modules

3, combined with the example of this article, consult the relevant APIs to practice

4,socket communication ideas between client and server side

5, be interested in perfecting the example of that chat room

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.