Big Bear nodejs------NET Module

Source: Internet
Author: User

First, the opening analysis

From today onwards, we have to delve into specific module learning, this article is the series (Big Bear Nodejs) article of the third article, the first two is mainly based on theory, I believe we in the first two study,

Nodejs also has a basic understanding, nothing!!! The strike, let us continue to Nodejs to the end, good nonsense 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 TCP-based encapsulation, the latter is essentially TCP layer, but do more data encapsulation, we see as the performance layer .

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

It is not difficult to see that Httpserver inherits the net class, has the related communication ability, has done the more data encapsulation, we regard as the more advanced performance layer.

Expand your knowledge (below is the source of "inherits"):

1Exports.inherits =function(ctor, Superctor) {2Ctor.super_ =Superctor;3Ctor.prototype =object.create (Superctor.prototype, {4 constructor: {5 Value:ctor,6Enumerablefalse,7Writable:true,8Configurable:true9     }Ten   }); One};

The 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 the Transport Layer protocol, which mainly solves how data is transmitted in the network.

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

(3), HTTP------HTTP is an application-layer protocol that primarily addresses how data is packaged.

(4), Network seven layer model------ The physical layer, the data link layer, the network layer, the Transport layer, the session layer, the presentation layer, and the application layer.

  To summarize: Thesocket is an encapsulation of the TCP/IP protocol, and the socket itself is not a protocol, but a calling interface (API).

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

TCP/IP is just a protocol stack, just like operating system operation mechanism, must be implemented specifically, but also to provide external operating interface

In fact, the transport layer TCP is based on the network layer of IP protocol, and the application layer of the HTTP protocol is based on the transport layer of the TCP protocol, and the socket itself is not a protocol, as mentioned above, it just provides a TCP or UDP programming interface.

Two, experience a

Well, we've got the concept, and here's an example:

1, establish server.js

1 varNET = require (' net ') ;2 varServer = Net.createserver (function(c) {//Connection Listener3Console.log ("Server is connected") ;4C.on ("End",function() {5Console.log ("Server Disconnected") ;6   }) ;7C.write ("Hello,bigbear!\r\n") ;8 C.pipe (c);9 }) ;TenServer.listen (8124,function() {//Listening Listener OneConsole.log ("Server is bound") ; A}) ;

2, establish client.js

1 varNET = require (' net ') ;2 varClient =Net.connect ({3port:81244},function(){//Connect Listener5Console.log ("Client Connected") ;6Client.write (' Hello,baby!\r\n ') ;7 });8Client.on ("Data",function(data) {9 Console.log (data.tostring ());Ten client.end (); One }); AClient.on ("End",function(){ -Console.log ("Client Disconnects") ; -}) ;

Analysis:

Service-side ------ net.createServer Create a TCP service, this service binding (Server.listen) on the 8124 port, after creating the server we see a callback function,

A parameter is passed in when the function is called, which is also a function, and accepts the socket, which is constructed by another method (pipe), which is used to interact with the data.

Pipe requires client to greet the server to establish, if there is no client access to the server, the socket will not exist.

客户端------net.connectAs the name implies, is connected to the server side, the first parameter is the object, set port 8124, that is, our servers listen to the port, because the host parameter is not set, the default is localhost (local).

In Server, the socket is one end of the pipeline, and in the client, the client itself is one end of the pipeline, and if multiple client connections Server,server creates multiple sockets, each of which corresponds to a client.

Operation Result:

Third, the introduction of the case

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

1 //Sever--one-way Client communication2 varNET = require (' net ');3 4 varChatserver =net.createserver ();5 6Chatserver.on (' Connection ',function(client) {7Client.write (' hi!\n ');//The server outputs information to the client, using the Write () method8Client.write (' bye!\n ');9 TenClient.end ();//the server ends the session One }); A  -Chatserver.listen (9000);

Telnet test: Telnet 127.0.0.1:9000

After you perform telnet, connect with the service point, feedback hi! bye! And immediately ends the service-side program terminating the connection.

What if we want the service to receive information about the client?

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

(2), listen for the Server.data event and do not abort the connection (otherwise you will end up receiving messages from the client immediately).

1 //On the basis of the former, the Client-to-Sever communication is realized, so that the two-way communication2 varNET = require (' net ');3 varChatserver =net.createserver (),4Clientlist = [];5     6Chatserver.on (' Connection ',function(client) {7//JS can add properties to objects freely. Here we add a custom property of name to indicate which client (client's address + port is based)8Client.name = client.remoteaddress + ': ' +Client.remoteport; 9Client.write (' Hi ' + client.name + '!\n ')); Ten clientlist.push (client);  OneClient.on (' Data ',function(data) { ABroadcast (data, client);//accept information from the client -   }); - }); the functionbroadcast (message, client) { - for(varI=0;i<clientlist.length;i+=1) {     -if(Client!==Clientlist[i]) {       -Clientlist[i].write (client.name + "says" +message);  +       }   -     } + } AChatserver.listen (9000);

Is the code above a full-featured one? We say there is another problem that is not considered: once a client exits, it remains in Clientlist, which is obviously a null pointer.

(3), handling clientlist

1Chatserver.on (' Connection ',function(client) {2Client.name = client.remoteaddress + ': ' +Client.remoteport3Client.write (' Hi ' + client.name + '!\n '));4 5 clientlist.push (client)6 7Client.on (' Data ',function(data) {8 Broadcast (data, client)9   })Ten  OneClient.on (' End ',function() { AClientlist.splice (Clientlist.indexof (client), 1);//deletes the set element in the array.  -   }) -})

The Node TCP API has provided us with an end event that occurs when the client aborts the connection to the server.

(4), optimize broadcast

1 functionbroadcast (message, client) {2   varCleanup = []3    for(varI=0;i<clientlist.length;i+=1) {4     if(Client!==Clientlist[i]) {5 6       if(clientlist[i].writable) {//Check if sockets is writable first7Clientlist[i].write (client.name + "says" +message)8}Else {9Cleanup.push (Clientlist[i])//if not writable, collect them and destroy them. Socket.destroy () is destroyed by the API before destroying it. Ten Clientlist[i].destroy () One       } A  -     } -}//Remove dead Nodes out of write loop to avoid trashing loop index the    for(i=0;i<cleanup.length;i+=1) { -Clientlist.splice (Clientlist.indexof (Cleanup[i]), 1) -   } -}

Note that once the "end" is not triggered, an exception occurs, so the optimization work is done.

(5), the Net API also provides an error event to catch the client's exception

function (e) {  console.log (e);});

Four, summarize

1, understanding the relevant concepts of the opening

2. Understanding the relationship between HTTP and net modules

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

4,socket communication ideas between client and server side

5, interested to complete the example of the chat room

      hahaha, the end of this article, not to be continued, hope and we have enough communication, common progress ... To shout ... (*^__^*)

Big Bear nodejs------NET Module

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.