Node. js advanced core module. net introduction and instance description module Overview
The net module is also the core module of nodejs. As mentioned in the overview of the http module, http. Server inherits net. Server. In addition, communication between the http client and the http Server is dependent on socket (net. Socket ). That is to say, for node Server programming, net is basically a module that cannot be bypassed.
From the perspective of composition, the net module mainly consists of two parts. Those who know socket programming should be familiar with the following:
Net. Server: TCP server, which can communicate with clients through socket.
Net. Socket: node Implementation of tcp/local socket, which implements full-duplex stream interface.
This article starts with a simple tcp server/client example to give readers a brief introduction. Next, we will introduce the important APIs, attributes, and events of net. Server and net. Socket respectively.
For beginners, it is recommended that you run the example in this article for better understanding.
Simple server + client example
The tcp server program is as follows:
Var net = require ('net'); var PORT = 3000; var HOST = '2017. 0.0.1 '; // tcp server var server = net. createServer (function (socket) {console. log ('server: receiving requests from the Client '); socket. on ('data', function (data) {console. log ('server: received client data, content: {'+ data +'} '); // return data socket to the client. write ('Hello, I am a Server');}); socket. on ('close', function () {console. log ('server: client disconnected ');}) ;}); server. listen (PORT, HOST, function () {console. log ('server: Start listening for requests from the Client ');});
The tcp client is as follows:
Var net = require ('net'); var PORT = 3000; var HOST = '2017. 0.0.1 '; // tcp client var client = net. createConnection (PORT, HOST); client. on ('connect ', function () {console. log ('client: connected to the server ');}); client. on ('data', function (data) {console. log ('client: received server data, content: {'+ data +'} ') ;}); client. on ('close', function (data) {console. log ('client: disconnected ');}); client. end ('Hello, I am a Client ');
Run the server and client code. The console outputs the following:
Server:
Server: Start listening for requests from the client
Server: receives a request from the client.
Server: receives client data. The content is {Hello, I am a client}
Server: the client is disconnected.
Client:
Client: You have established a connection with the server.
Client: receives data from the server. The content is {Hello, I am the server}
Client: disconnected
Server net. Server
Server. address ()
Return the address information of the server, such as the bound IP address and port.
Console. log (server. address (); // The output is as follows: {port: 3000, family: 'ipv4 ', address: '2017. 0.0.1 '}
Server. close (callback])
Shut down the server and stop receiving new client requests. Note:
For client requests that are being processed, the server will wait for them to finish processing (or time out), and then officially close them.
When the function is normally disabled, the callback is executed and the close event is triggered.
When an exception is disabled, callback is executed and the corresponding error is passed as a parameter. (For example, server. close () is called before server. listen (port) is called ())
The following two examples are used to compare and list the conclusions.
Server. listen () called: close normally, close event is triggered, and then callback is executed. The error parameter is undefined.
Server. listen () not called: closes an exception. The close event is triggered and then callback is executed. error indicates the specific error message. (Note: The error event is not triggered)
Example 1: the server is shut down normally.
Var net = require ('net'); var PORT = 3000; var HOST = '2017. 0.0.1 '; var noop = function () {}; // tcp server var server = net. createServer (noop); server. listen (PORT, HOST, function () {server. close (function (error) {if (error) {console. log ('close callback: Server exception: '+ error. message);} else {console. log ('close callback: the server is closed normally ') ;}}) ;}); server. on ('close', function () {console. log ('close event: server shut');}); server. on ('error', function (error) {console. log ('error event: Server exception: '+ error. message );});
Output:
Close event: the server is closed.
Close callback: the server is closed normally.
Example 2: Server exception Shutdown
The Code is as follows:
Var net = require ('net'); var PORT = 3000; var HOST = '2017. 0.0.1 '; var noop = function () {}; // tcp server var server = net. createServer (noop); // The request listening is not officially started // server. listen (PORT, HOST); server. on ('close', function () {console. log ('close event: server shut');}); server. on ('error', function (error) {console. log ('error event: Server exception: '+ error. message) ;}); server. close (function (error) {if (error) {console. log ('close callback: Server exception: '+ error. message);} else {console. log ('close callback: the server is closed normally ');}});
Output:
Close event: the server is closed.
Close callback: Server exception: Not running
Server. ref ()/server. unref ()
Those who know node event loops should be familiar with these two APIs. They are mainly used to remove servers from the event loops and remove servers from the event loops. The impact is whether the process exits.
For those who come out to learn net, they don't need to pay special attention. If you are interested, just do the experiment yourself.
Event listening/connection/close/error
Listening: Calls server. listen () and is triggered when a listener is started.
Connection: triggered when a new request comes in. The parameter is the socket related to the request.
Close: triggered when the server is closed.
Error: triggered when a service error occurs, for example, listening to the occupied port.
Several events are relatively simple. Here is only an example of connection.
The test results show that when a new client connection is generated, the callback in net. createServer (callback) is called, and the callback function registered by the connection event is also called.
In fact, the callback in net. createServer (callback) also adds a listener function as a connection event in the node internal implementation. If you are interested, you can refer to the node source code.
Var net = require ('net'); var PORT = 3000; var HOST = '2017. 0.0.1 '; var noop = function () {}; // tcp server var server = net. createServer (function (socket) {socket. write ('1. connection triggering \ n');}); server. on ('connection', function (socket) {socket. end ('2. connection triggering \ n');}); server. listen (PORT, HOST );
Run the following command to test the effect:
Curl http: // 127.0.0.1: 3000
Output:
1. connection trigger
2. connection trigger
Client net. Socket
I have already mentioned the client-side example at the beginning of the article. I will post the example here. (Note: net. Socket should not be called a client strictly. It is easy to explain here)
From the official node documentation, it seems that net. Socket is much more complicated than net. Server, and has more APIs, events, and attributes. However, if you classify the APIS, events, and attributes related to net. Socket, you will find that they are not very complex.
For more information, see the next section.
Var net = require ('net'); var PORT = 3000; var HOST = '2017. 0.0.1 '; // tcp client var client = net. createConnection (PORT, HOST); client. on ('connect ', function () {console. log ('client: connected to the server ');}); client. on ('data', function (data) {console. log ('client: received server data, content: {'+ data +'} ') ;}); client. on ('close', function (data) {console. log ('client: disconnected ');}); client. end ('Hello, I am a Client ');
API and attribute classification
The following describes the API and attributes of net. Socket, which are roughly classified by purpose to facilitate your understanding. Most of the APIs and attributes are relatively simple. You will know what to do after reading the documentation.
Connection problems
Socket. connect (): There are three different parameters for different scenarios;
Socket. setTimeout (): Used to set connection timeout.
Socket. setKeepAlive (): Used to set persistent connections.
Socket. destroy () and socket. destroyed: When an error occurs, it is used to destroy the socket and ensure that no other IO operations are performed on the socket.
Data Reading and Writing
Socket. write (), socket. end (), socket. pause (), socket. resume (), socket. setEncoding (), socket. setNoDelay ()
Data attributes
Socket. bufferSize, socket. bytesRead, socket. bytesWritten
Event Loops
Socket. ref (), socket. unref ()
Address Problems
Socket. address ()
Socket. remoteAddress, socket. remoteFamily, socket. remotePort
Socket. localAddress/socket. localPort
Event Overview
Data: triggered when receiving data from the other side.
Connect: triggered when the connection is established.
Close: triggered when the connection is closed. If the connection is disconnected due to a transmission error, the parameter is error.
End: triggered when the FIN package is sent to the other side of the connection (the reader can review how HTTP is disconnected ). By default (allowHalfOpen = false), the socket will destroy itself. However, you can set allowHalfOpen to true to continue writing data to the socket. Of course, you need to manually call socket. end ()
Error: triggered when an error occurs. The parameter is error. (The Official Document contains only one sentence, but you can understand that there may be too many errors)
Timeout: indicates that the socket has timed out and the connection needs to be closed manually.
Drain: triggered when the write cache is empty. (It is not a good description. For details, refer to stream introduction)
Lookup: triggered when domain name resolution is complete.