Node. js-NET module _ node. js

Source: Internet
Author: User
The previous two articles are basically the theoretical basis of nodejs. let's start with the NET module. I. opening analysis

Starting from today, we will go deep into the specific modules. This article is the third article in this series. The first two articles mainly focus on theory. I believe that in the first two articles,

I also have a basic understanding of NodeJS. it's okay !!! Let's continue to implement NodeJS to the end. well, I don't need to talk much about it. I will go directly to the "Net module" topic today. how should I understand "Net?

What is it? (NetThe module can be used to create a Socket server or Socket client. For NodeJS data communication, the two most basic modules are Net and Http. The former is based on Tcp encapsulation, and the latter is essentially a Tcp layer, but it only implements a lot of data encapsulation, we think of it as a performance layer ).

Refer to the source code in NodeJS "http. js" here:

It is not hard to see that HttpServer inherits the Net class, has the relevant communication capability, and has made a lot of data encapsulation. we think of it as a more advanced presentation layer.

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

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,
Retriable: true
}
});
};

The function is inherited and reused.

I just gave a brief overview of some common concepts. here is a brief introduction to the concept popularization:

(1), TCP/IP ------ TPC/IP protocol is the transport layer protocol, mainly to solve how data is transmitted in the network.

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

(3) Http ------ HTTP is an application layer protocol, mainly used to package data.

(4) layer-7 network model ------ physical layer, data link layer, network layer, transmission layer, session layer, presentation layer, and application layer.

To sum up, the Socket is an encapsulation of the TCP/IP protocol. the Socket itself is not a protocol, but an API ).

This forms some of the most basic function interfaces we know, such as Create, Listen, Connect, Accept, Send, Read, and Write.

TCP/IP is just a protocol stack. like the operating mechanism of the operating system, it must be implemented in detail and provide external operation interfaces.

In fact, the TCP at the transport layer is based on the IP protocol at the network layer, while the HTTP protocol at the application layer is based on the TCP protocol at the transport layer, and the Socket itself is not a protocol, as mentioned above, it only provides an interface for TCP or UDP programming.

2. try it

Now, we have the following concepts:

1. create server. js

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 disconnected ");
});
C. write ("Hello, Bigbear! \ R \ n ");
C. pipe (c );
});
Server. listen (8124, function () {// Listening listener
Console. log ("server bound ");
});

2. create client. js

The code is as follows:


Var net = require ('net ');
Var client = net. connect ({
Port: 8124
}, Function () {// connect listener
Console. log ("client 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 ");
});

Analysis:

Server ------net.createServerCreate a TCP service and bind the service (server. listen) to Port 8124. after creating the Server, we can see a callback function,

When calling the above function, input a parameter. this parameter is also a function and accepts socket, a pipeline constructed by other methods (pipe ), it is used for data interaction.

Pipe can be created only when the Client greets the Server. If no Client accesses the Server at the moment, this socket will not exist.

Client ------ net. connectAs the name suggests, it is to connect to the server. The first parameter is the object, and the port is set to 8124, that is, the port listened to by our server. because the host parameter is not set, the default value is localhost (local ).

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

Running result:

III. case introduction

(1) the following code only outputs a piece of text from the server to the client to complete one-way communication between the server and the client.

The code is as follows:


// Sever --> Client 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 end the session
});
Chatting server. listen (9000 );

Telnet: telnet127.0.0.1: 9000

After telnet is executed, connect to the service point and report to Hi! Bye! And immediately end the server program to terminate the connection.

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

You can listen to server. data events and do not stop the connection (otherwise, messages from clients cannot be accepted immediately ).

(2) listen to the server. data event and do not stop the connection (otherwise, the client cannot receive messages immediately ).

The code is as follows:


// Implement Client-> Sever communication based on the former, so that bidirectional communication is realized.
Var net = require ('net ');
Var chatServer = net. createServer (),
ClientList = [];
ChatServer. on ('connection', function (client ){
// JS can freely add attributes to objects. Here we add a name custom attribute to indicate which client (based on the client 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); // receives information from the client
});
});
Function broadcast (message, client ){
For (var I = 0; I If (client! = ClientList [I]) {
ClientList [I]. write (client. name + "says" + message );
}
}
}
Chatting server. listen (9000 );

Is the above a complete functional code? Let's say there is another problem not taken into account: that is, once a client exits, it is still stored in the clientList, which is obviously a null pointer.

(3) process the clientList

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 an end event for us, that is, when the client terminates the connection with the server.

(4) optimizing broadcast

The code is as follows:


Function broadcast (message, client ){
Var cleanup = []
For (var I = 0; I If (client! = ClientList [I]) {
If (clientList [I]. writable) {// check whether sockets is writable.
ClientList [I]. write (client. name + "says" + message)
} Else {
Cleanup. push (clientList [I]) // if it cannot be written, collect it and destroy it. Before destruction, use the API method to destroy Socket. destroy.
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 occurs, so optimization is performed.

(5) NetAPI also provides an error event to capture client exceptions.

The code is as follows:


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

IV. Summary

1. understand the concepts at the beginning

2. understand the relationship between Http and Net modules

3. use the example in this article to check related APIs for practice.

4. communication between the socket client and the server

5. if you are interested, you can improve the example of the 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.