Nodejs Advanced: Core Module NET Introductory learning and example explanation _node.js

Source: Internet
Author: User
Tags socket

Module overview

NET module is also the core module of Nodejs. As mentioned in the overview of HTTP modules, HTTP. The Server inherits Net.server, and the HTTP client communicates with the HTTP server on the Socket (Net.socket). In other words, to do node-server programming, NET is basically a module that can't be bypassed.

From the composition, the net module contains two parts, to understand the socket programming students should be more familiar with:

    • Net. Server:tcp server, internally through the socket to achieve communication with the client.
    • Net. Socket:tcp/is implemented with the node version of the local socket, which implements a Full-duplex stream interface.

This article starts with a simple example of a TCP server/client, so that the reader can have an overview. Then we'll introduce net separately. Server, net. Socket more important APIs, properties, events.

For beginners, it is advisable to run the example of the article in a local context to deepen understanding.

Simple examples of server+client

The TCP server-side program is as follows:

var net = require (' net ');

var PORT = 3000;
var HOST = ' 127.0.0.1 ';

TCP service-side
var server = net.createserver (function (socket) {
  console.log (' Server: Receive request from client ');

  Socket.on (' Data ', function (data) {
    console.log (' Server: Receive client data, content is {' + Data + '} ');

    Return data to
    the client socket.write (' Hello, I am the service side ');
  };

  Socket.on (' Close ', function () {
     console.log (' Server: Client connection disconnected ');
  }
); Server.listen (port, HOST, function () {
  console.log (' Server: Start listening for requests from client ');


TCP clients are as follows:

var net = require (' net ');

var PORT = 3000;
var HOST = ' 127.0.0.1 ';

TCP Clients
var client = net.createconnection (PORT, HOST);

Client.on (' Connect ', function () {
  Console.log (' Client: Connection has been established with the server ');
});

Client.on (' Data ', function (data) {
  Console.log (' Client: Receive server-side data, content is {' + Data + '} ');
};

Client.on (' Close ', function (data) {
  Console.log (' Client: Disconnected ');
};

Client.end (' Hello, I'm client ');

Run the server side, the client code, the console output is as follows:

Service side:

Service side: Start listening for requests from clients
Service side: Receive request from client
Service side: Receive client data, content is {hello, I am the client}
Server side: Client connection disconnected

Client:

Client: Connection has been established with the server
Client: Receive server data, content is {hello, I am service side}
Client: Connection disconnected

Service-side net. Server

Server.address ()
Returns the address information of the server, such as the bound IP address, port, and so on.

Console.log (Server.address ());
The output is as follows {port:3000, family: ' IPv4 ', Address: ' 127.0.0.1 '}

Server.close (callback])

Shut down the server and stop receiving new client requests. There are a few things to note:

    • For client requests that are being processed, the server waits for them to finish (or timeout) before it is formally closed.
    • At the same time as normal shutdown, callback is executed and the close event is triggered.
    • When the exception is closed, the callback also executes, and the corresponding error is passed in as a parameter. (for example, before calling Server.listen (port), you call Server.close ())

The following two specific examples will be compared to the first to list the conclusions

    • Called Server.listen (): Normal shutdown, close event trigger, then callback execution, error parameter is undefined
    • Server.listen () is not invoked: The exception is closed, the close event is triggered, and then callback executes, and error is the exact wrong message. (Note that the error event is not triggered)

Example 1: Server end normal shutdown

var net = require (' net ');
var PORT = 3000;
var HOST = ' 127.0.0.1 ';
var noop = function () {};

TCP Service
-side var server = Net.createserver (noop);

Server.listen (PORT, HOST, function () {

  server.close (function (Error) {
    if (error) {
      console.log) (' Close callback: Server-side exception: ' + Error.message ';
    } else{
      Console.log (' Close callback: server-side normal shutdown ')
    ;

}); Server.on (' Close ', function () {
  console.log (' Closing event: Server closed ');
};

Server.on (' Error ', function (error) {
  console.log (' Error Event: Server exception: ' + Error.message ';
});

The output is:

Close event: Service side shutdown
Close callback: Server end normal shutdown

Example 2: Server-side exception shutdown

The code is as follows

var net = require (' net ');
var PORT = 3000;
var HOST = ' 127.0.0.1 ';
var noop = function () {};

TCP Service
-side var server = Net.createserver (noop);

No formal launch request listening
//Server.listen (PORT, HOST);

Server.on (' Close ', function () {
  console.log (' Closing event: Server closed ');
};

Server.on (' Error ', function (error) {
  console.log (' Error Event: Server exception: ' + Error.message ';
});

Server.close (the function (error) {if (error) {
    console.log (' Close callback: Server-side exception: ' + error.message);
  } else{
    Console.log (' Close callback: server-side normal shutdown ');
  }      
);

The output is:

Close event: Service side shutdown
Close callback: Server-side exception: not running

Server.ref ()/server.unref ()

Understand the node event loop students should be familiar with these two APIs, mainly for the server to join the event loop/from the event loop to remove, the impact is whether the process will affect the exit.

For the students to learn net, do not need special attention, interested in doing their own experiment is good.

Event Listening/connection/close/error

    • Listening: Invokes Server.listen () and triggers when the listening request is formally started.
    • Connection: Triggers when a new request comes in, and the parameter is the socket associated with the request.
    • Close: Triggers when the service end is closed.
    • ERROR: Triggers when a service fails, such as listening on a port that has already been occupied.

Several events are relatively simple, and here are just a connection example.

As you can see from the test results, when a new client connection is generated, the callback callback in Net.createserver (callback) is invoked, and the callback function that connection event registration is invoked.

In fact, callback in Net.createserver (callback) also joins the listener function as a connection event within the node's internal implementation. Interested can see the source of node.

var net = require (' net ');
var PORT = 3000;
var HOST = ' 127.0.0.1 ';
var noop = function () {};

TCP service-side
var server = net.createserver (function (socket) {
  socket.write (' 1. Connection trigger \ n ');

Server.on (' Connection ', function (socket) {
  socket.end (' 2. Connection trigger \ n ');
});

Server.listen (PORT, HOST);

Test the effect with the following command

Curl http://127.0.0.1:3000

Output:

1. Connection Trigger
2. Connection Trigger

Client Net. Socket

At the beginning of the article has raised the example of the client, here to put the example to paste. (remark: Strictly should not put net. Socket is called client, here is easy to explain.

From the official document of node, I feel net. Socket than net. The Server is much more complex, with more APIs, events, and properties. But actually, put net. Socket-related APIs, events, attributes are categorized, you will find, in fact, is not particularly complex.

Please see the next section for details.

var net = require (' net ');

var PORT = 3000;
var HOST = ' 127.0.0.1 ';

TCP Clients
var client = net.createconnection (PORT, HOST);

Client.on (' Connect ', function () {
  Console.log (' Client: Connection has been established with the server ');
});

Client.on (' Data ', function (data) {
  Console.log (' Client: Receive server-side data, content is {' + Data + '} ');
};

Client.on (' Close ', function (data) {
  Console.log (' Client: Disconnected ');
};

Client.end (' Hello, I'm client ');

APIs, attribute collations

The following pair of net. Socket API and attributes, according to the use of the general classification, to facilitate a better understanding of the reader. Most of the API and attributes are simple, look at the document to know what to do, here is not to start.

Connection related

    • Socket.connect (): There are 3 different parameters for different scenarios;
    • Socket.settimeout (): Used for connection timeout settings.
    • Socket.setkeepalive (): Used to set up long connections.
    • Socket.destroy (), socket.destroyed: When the error occurs, to destroy the socket, to ensure that the socket will not have other IO operation.

Data read and write related

Socket.write (), Socket.end (), Socket.pause (), Socket.resume (), socket.setencoding (), Socket.setnodelay ()

Data attribute related

Socket.buffersize, Socket.bytesread, Socket.byteswritten

Event Loop related

Socket.ref (), Socket.unref ()

Address related

    • Socket.address ()
    • Socket.remoteaddress, socket.remotefamily, Socket.remoteport
    • Socket.localaddress/socket.localport

Introduction to Events

    • Data: Triggered when a message is received from the other side.
    • Connect: Triggered when connection is established.
    • Close: Triggered when the connection is disconnected. If the connection caused by the transmission error is disconnected, the parameter is error.
    • End: Triggers when the other side of the connection sends a FIN packet (the reader can review how HTTP is disconnected). By default (Allowhalfopen = = false), the socket completes the self-destruct operation. But you can also set the Allowhalfopen to true so that you can continue to write data into the socket. Of course, at the end you need to manually invoke Socket.end ()
    • Error: When a fault occurs, it is triggered, and the parameter is error. (The official document is basically a sentence, but considering that there may be too many mistakes, it can be understood)
    • Timeout: Prompts the user that the socket has timed out and needs to manually close the connection.
    • Drain: Triggers when the write cache is empty. (Not very good description, specific can see the introduction of the stream)
    • Lookup: Triggered when domain name resolution completes.

RELATED LINKS

Official documents: Https://nodejs.org/api/net.html#net_socket_destroy_exception

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.