Node. js network communication module implementation analysis, node. js Network Communication

Source: Internet
Author: User
Tags socket error

Node. js network communication module implementation analysis, node. js Network Communication

Preface

Presumably, we should use Node. js most to create http services. Therefore, for every Web Development Engineer, Node. js network-related module learning is essential.

Node. js Network Module Architecture

In the Node. js module, network-related modules include:Net, DNS, HTTP, TLS/SSL, HTTPS, UDP/datasyncIn addition, there are also V8's underlying network modulestcp_wrap.cc,udp_wrap.cc,pipe_wrap.cc,stream_wrap.ccAnd so on. The Javascript layer and the C ++ layer communicate with each other through process. binding.

Net Module

The Net module provides some underlying network communication interfaces, including creating servers and clients. The HTTP module is also an upper-layer encapsulation based on the Net model. The Net module mainly provides net. server and net. socket

Create a TCP Server

Create a TCP server by using Constructornew net.ServerOr use the factory Methodnet.createServerBoth methods return a net. Server class, which can receive two optional parameters.

Var net = require ('net'); var server = net. createServer (function (socket) {socket. on ('data', function (data) {console. log ('socket data', data. toString (); socket. write (data. toString ());}). on ('end', function () {console. log ('socket end ')}). on ('error', function (error) {console. log ('socket error', error) ;}); server. listen (56200, function () {console. log ('server run at', server. address () ;}); server. on ('error', function (err) {throw err;}); // after execution: server run at {address: ', family: 'ipv6 ', port: 56200}

If no port is specified during listen listening, a port is automatically monitored. After a TCP server is createdtenlent 0.0.0.0 56200After the link, you can communicate with the server. PasscreateServerAfter a service is instantiated, the service listens to client requests. After a link is established with the client, the link will be thrown in the callback.net.SocketObject.

Create a TCP client

You can use constructor to create a TCP client link.new net.SocketOr its factory Methodnet.createConnection. A net. Socket instance is returned after the instance is created successfully.

var net = require('net');var client = net.createConnection({port:56200,host:'localhost'});client.on('connect',function(){  console.log('client connect');});client.on('data',function(data){  console.log('client data',toString());});client.on('error',function(error){  throw error;});client.on('close',function(){  console.log('client close');});

Socket

The socket is not described in detail here. Next we will mainly learn about the methods provided by the net. Socket constructor and the use of listener events.

Related Events

  1. Connect: triggered when a connection is successfully established between the client and the server. If the connection fails, the server directly throws an error and exits the node process.
  2. Data: triggers a callback when the client receives the data sent by the server or the data sent by the client to the server.
  3. End: triggered when the FIN packet sent from the other side is disconnected. By default (allowHalfOpen == false) The socket will destroy itself (if the response packet is not officially returned to the queue to be written), but we can setallowHalfOpenThe parameter is true, so that you can continue writing data to the socket, but we need to call the end method to consume this socket, otherwise it may cause handle leakage.
  4. Close: triggered when the link is disconnected, but if an error occurs during transmission, an error is thrown in the callback function.
  5. Timeout: triggered when the socket times out and is idle. To destroy it in the queue, you must manually call the close method.
  6. Lookup: triggered when domain name resolution is complete.
  7. Drain: triggered when the cache is written. It can be used in the upload size limit.

Related Methods

  1. Write (): the service end sends data to the client or the client sends data to the server.
  2. Address (): Obtain the IP address of the socket bound to the service. The returned object has three attributes: Port, host, and
  3. And IPvX.
  4. End (): If the socket is half closed, a FIN package will be sent, and the server may still send some data. You can also call socket. end (data, encoding) like this ).
  5. Pause (): stops reading data and can be used as a limit on data upload.
  6. Resume (): continue reading data.
  7. SetEncoding (): sets the data stream acquisition format.
  8. SetKeepAlive (): allows/disables the keep-alive function.
  9. SetNoDelay (): Disable the Nagele algorithm. By default, the Nagle algorithm is used for TCP links. Data is cached before being sent. If this is true, the data will be sent immediately each time socket. write (). The default value is true.
  10. SetTimeout (): the number of seconds after which an idle socket is inactive will receive the timeout event, but the socket will not stop destruction. You need to manually call end () or destroy (). Indicates that the idle time is disabled.

Related attributes

  1. BufferSize: the number of cached strings waiting to be sent.
  2. BytesRead: number of bytes received.
  3. BytesWritten: number of bytes sent
  4. Destroyed: identifies whether a link has been damaged. Once the link is broken, you do not need to use this link to transmit data.
  5. LocalAddress: the host of the local address linked to the remote client. If the host of the listening service is 0.0.0.0 and the client is connected to '192. 168.1.1 ', the last value is the latter.
  6. LocalPort: local port.
  7. RemoteAddress: Client IP address. If the socket is already destryed, the value isundefined.
  8. RemoteFamily: the client is named snapshot X.

Return packet Exception Handling

After the server receives the data to be processed from the client, it enters the processing stage. If the data is disconnected outside the socket before the business logic processing is completed, the server will directly respond when the server returns the data to the client.errorEvent and Error:This socket has benn ended by the other partTherefore, before the return, the server must first determine whether the socket is destroyed. If the socket is not destroyed, the return packet is returned. If the socket is disconnected, the socket is destroyed:

var net = require('net');var biz = require('./biz');var server = net.createServer(function(socket){  socket    .on('data',function(data){      biz.do(data)        .then(function(){          if( !socket.destroyed ) {            socket.write( data.toString() );          } else {            // do some report            socket.destry();          }        })        .catch(function(){          !socket.destroyed && socket.end('server handler error');        });          })    .on('end',function(){      console.log('socket end')    })    .on('error',function(error){      console.log('socket error',error);    });});server.listen(56200,function(){  console.log('server run at ',server.address());});server.on('error',function(err){  throw err;});

Restrict client data size

The request size limit is an essential part of service security. The server cannot accept all the data sent from the client infinitely, And the size limit is the first threshold.

var net = require('net');var MAX_REQUEST_BYTES = 2 * 1024 * 1024; // 2Mvar server = net.createServer(function(socket){  socket    .on('data',function(data){            if(data.bytesRead > MAX_REQUEST_BYTES) {        socket.pause();        socket.end('data is too big, forbidden');        // do some report      }    })    .on('end',function(){      console.log('socket end')    })    .on('error',function(error){      console.log('socket error',error);    });});server.listen(56200,function(){  console.log('server run at ',server.address());});server.on('error',function(err){  throw err;});

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.