Home > Web Front-end > JS Tutorial > body text

Detailed explanation of the implementation method of network communication module in Node.js

巴扎黑
Release: 2017-08-16 11:54:38
Original
1610 people have browsed it
Preface
Presumably what we use Node.js the most is to create http services, so for every web development engineer, learning the network-related modules of Node.js is a must Indispensable.
Network module architecture of Node.js
In the Node.js module, network-related modules include Net, DNS, HTTP, TLS/SSL, HTTPS, UDP/Datagram. In addition, there are The network modules related to the bottom layer of v8 include tcp_wrap.cc, udp_wrap.cc, pipe_wrap.cc, stream_wrap.cc, etc. The Javascript layer and the C++ layer communicate with each other through process.binding.
Detailed explanation of the implementation method of network communication module in Node.js

Net module
Net module provides some underlying network communication interfaces, including creating servers and clients. The HTTP module is also based on the Net model. The upper layer encapsulation, the Net module mainly provides net.Server and net.Socket
Create TCP server
To create a TCP server, you can use the constructor new net.Server or use the factory Method net.createServer, both methods will return a net.Server class that 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;});// 执行后:server run at { address: '::', family: 'IPv6', port: 56200 }
Copy after login

If no port is specified when listening, it will automatically listen to a port at will. After creating a TCP server, use tenlent 0.0.0.0 56200, and data communication with the server can be performed after the connection. After instantiating a service through createServer, the service will listen to client requests. After establishing a link with the client, the net.Socket object for link building will be thrown in the callback.
Create TCP client
To create a TCP client link, you can use the constructor new net.Socket or its factory method net.createConnection. After successful creation, a net.Socket instance will be returned.
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');});
Copy after login

Socket
I won’t go into detail about what socket is. Let’s take a look at the main methods and use of listening events provided by the net.Socket construct. .
Related events
connect: Triggered when the client successfully establishes a link with the server. If the connection fails, the server will directly throw an error event and exit the node process.
data: A callback is triggered when the client receives data sent from the server or data sent from the client to the server.
end: Triggered when the other side sends a FIN packet and is disconnected. By default (allowHalfOpen == false) the socket will self-destruct (if it is written to the pending queue and the return packet has not been officially responded to), but we can Set the allowHalfOpen parameter to true, so that you can continue to write data to the socket, but we need to call the end method ourselves to consume the socket, otherwise it may cause handle leakage.
close: Triggered when the link is disconnected, but if there is an error during the transmission, an error will be thrown in the callback function.
timeout: Triggered when the socket times out and is idle. If you want to destroy it in the queue, you need to manually call the close method.
lookup: Triggered when domain name resolution is completed.
drain: Triggered when the cache is written, and can be used to limit the upload size.
Related methods
write(): The server sends data to the client or the client sends data to the server.
address(): Get the IP address of the socket bound to the service. The returned object has three attributes, namely port, host,
and IPvX version.
end(): Half-close the socket and a FIN packet will be sent. The server may still send some data. You can also call socket.end(data,encoding) like this.
pause(): Pauses reading data and can be used to limit data upload.
resume(): Continue data reading.
setEncoding(): Set the acquisition format of the data stream.
setKeepAlive(): Allow/disable the keep-alive function.
setNoDelay(): Disable the Nagele algorithm. TCP links use the Nagle algorithm by default, and their data will be cached before sending. If this is true, data will be sent immediately every time socket.write() is called. The default is true.
setTimeout(): When an idle socket is inactive for a few seconds, it will receive a timeout event, but the socket will not stop being destroyed, and you need to manually call end() or destroy(). Indicates that idle timeout is prohibited.
Related properties
bufferSize: The number of currently buffered strings waiting to be sent.
bytesRead: Number of bytes received.
bytesWritten: The number of bytes sent
destroyed: Identifies whether the link has been destroyed. Once it is destroyed, the link does not need to be used to transmit data.
localAddress: The host to which the remote client connects to the local address. If the host of our listening service is 0.0.0.0, and the client connection is '192.168.1.1', the final value is the latter.
localPort: local port.
remoteAddress: Client IP, if the socket is destroyed, the value is undefined.
remoteFamily: The client is IPvX
Packet return exception processing
The server enters the processing link after receiving the data that needs to be processed from the client. If the socket is interrupted before the business logic processing is completed, If it is turned on, when the server reports back to the client, it will directly respond to the error event and report Error: This socket has benn ended by the other part. Therefore, before reporting back, the server needs to first determine whether the socket has been destroyed. If it has not been destroyed, Then return the packet, and destroy it if it has been disconnected:
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;});
Copy after login

Limit client data size
对请求大小限制是服务安全里面比不可少的一个环节,服务端不能无限大小的去接受客户端发送过来的所有数据,而限制大小就是第一道门槛。
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;});
Copy after login

The above is the detailed content of Detailed explanation of the implementation method of network communication module in Node.js. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template