The use of the net module of nodejs

netThe underlying ipc communication of vscode is encapsulated based on the node module. Today I will roughly explain the use of the net module.

Official document address: https://nodejs.cn/api/net.html

The role of the net module

The net module provides the ability to build tcpor ipcserver and client in a stream-based fashion.

The node:net module provides an asynchronous networking API for creating stream-based TCPor IPC servers ( net.createServer() ) and clients ( net.createConnection() ).

Introduction to TCP and IPC

The OSI reference model divides network communication functions into 7 layers, namely physical layer, data link layer, network layer, transport layer, session layer, presentation layer and application layer. The TCP protocol is a protocol at the transport layer.
insert image description here

TCP

TCP: Transmission Control Protocol, which can communicate between processes on the same machine or different machines or different operating systems.

tcp features

  • connection-oriented

Connection-oriented : It means that a connection must be established with the other party before formal communication; it is also the so-called three-way handshake.

The main purpose of the three-way handshake is to synchronize the sending and receiving of data packets.

The general process of the three-way handshake : 1. Client A sends a connection request packet to host B; 2. Host B sends a packet to client A agreeing to connect and request synchronization; 3. Client A sends another packet to confirm with the host B sync.

  • end to end

  • reliable

    • Application data is segmented into chunks of data that TCP deems most appropriate to send
    • When TCP sends a message segment, it starts a timer and waits for the destination to confirm receipt of the message segment; if it cannot receive a confirmation in time, it will resend the message segment.
    • When TCP receives data from the other end of the TCP connection, it sends an acknowledgment. This acknowledgment is not sent immediately, it is deferred.
    • TCP will maintain a checksum of its header and data. This is an end-to-end checksum to detect any changes in the data in transit. If the checksum of the received segment is incorrect, TCP will discard the segment and expect the sender to resend it.
    • Since TCP segments are transmitted as IP packets, and IP datagrams may arrive out of order, TCP segments may also arrive out of order. If necessary, TCP will reorder the received data, The received data is handed over to the application layer in the correct order. However, IP datagrams will be duplicated, and the receiving end of TCP will discard duplicate data.
    • TCP can also perform flow control. Each party of the TCP connection has a fixed-size buffer space, and the TCP receiver only allows the sender of the other party to send data that can be accommodated in the buffer of the receiver.

IPC

IPC: (Inter Process Communication) is inter-process communication, which can only communicate between different processes on the same machine, and cannot cross physical machines!!

Build a TCP server

In the process of creating a session between the TCP server and the client, the server and the client provide a socket (socket) respectively, and these two sockets form a connection together. The server and the client realize the connection operation between the two through the socket.

net.createServer([options][, connectListener])

  • options: object

  • alloHalfOpen: boolean, the default is false, then when the readable end ends, the socket will automatically end the writable end;

  • pauseOnConnect: boolean, default false, indicates whether the socket should be paused on incoming connections

  • connectLisetener: Function, which is a callback function when the client establishes a connection with the server. This callback function takes the socket port object as a parameter

  • return net.Server

import net from 'net';

const server = net.createServer((socket) => {
    
    
  console.log('client connect')
  /***********************net.Socket事件*******************************/
  // 接收到数据时触发。
  socket.on('data', (data) => {
    
    
    console.log(data.toString())
  })
  // 当成功建立套接字连接时触发。
  socket.on('connect', () =>{
    
    
    console.log('套接字建立成功')
  })
  // 当写缓冲区变空时触发。
  socket.on('drain', () => {
    
    })
  // 当套接字的另一端表示传输结束时触发,从而结束套接字的可读端。
  socket.on('end', () => {
    
    
    console.log('数据接受完毕')
  })
  // 发生错误时触发,close事件将在此事件之后直接调用
  socket.on('error', (err) => {
    
    
    console.log(err)
  })
  // 一旦套接字完全关闭就触发
  socket.on('close', (hasError) => {
    
    
    // 参数 hadError 是布尔值,表示套接字是否由于传输错误而关闭。ture则表示由于传输错误而导致关闭
  })
})
/***************************net.Server 属性*****************************/
// 最大连接数字,设置此属性以在服务器的连接计数变高时拒绝连接。
server.maxConnections = 6;

/***************************net.Server事件******************************/
// 建立新连接时触发
server.on('connection', (socket) => {
    
    
  
})
// 发生错误时触发
server.on('error', (err) => {
    
    
  
})
// 服务器关闭时触发
server.on('close', () => {
    
    
  
})

/****************************net.Server方法*******************************/
// 异步获取服务器上的并发连接数
server.getConnections((err, count) => {
    
    
  if (err) return
  console.log(count)
})
// 获取监听地址端口参数信息
const address = server.address();

// 绑定监听端口
server.listen(8124, () => {
    
    
  console.log('TCP Server is runing')
})
// 停止服务器接受新连接并保持现有连接。
server.close((err) => {
    
    
  // 该函数是异步的,当所有连接都结束并且服务器触发 'close' 事件时,则服务器最终关闭。
  // 如果服务器在关闭时未打开,它将以 Error 作为唯一参数被调用。
})

Build a TCP client

net.createConnection()

import net from 'net';
// 创建新的 net.Socket,并立即使用 socket.connect() 发起连接,然后返回启动连接的 net.Socket。
// 建立连接后,将在返回的套接字上触发 'connect' 事件。 最后一个参数 connectListener(如果提供)将作为 'connect' 事件的监听器添加一次。
const client = net.createConnection({
    
    
  port: 8124, // 端口
  host: '11.11.11.12', // 服务地址,默认localhost
}, () => {
    
    
  console.log('连接成功')
})
/*********************net.Socket 属性*************************/
// 接受的字节数
client.bytesRead = 1024;
// 发送的字节数
client.bytesWritten = 2048;
// 返回本地IP地址的字符串表示
client.localAddress
// 返回本地端口
client.localPort
// 远程 IP 地址的字符串表示形式
client.remoteAddress
// 远程 IP 系列的字符串表示形式。 'IPv4' 或 'IPv6'。
client.remoteFamily
// 远程端口的数字表示
client.remotePort
/*********************net.Socket 事件*************************/
// 连接server成功后触发
client.on('connect', () => {
    
    

})
// 接收到数据时触发
client.on('data', (data) => {
    
    
  console.log(data.toString())
})
// 当套接字的另一端表示传输结束时触发,从而结束套接字的可读端。
client.on('end', () => {
    
    })
// 当写缓冲区变空时触发。 可用于限制上传。
client.on('drain', () => {
    
    })
// 当套接字准备好使用时触发。
client.on('ready', () => {
    
    })
// 如果套接字因不活动而超时则触发。
client.on('timeout', () => {
    
    
  // 这只是通知套接字已空闲。 用户必须手动关闭连接。
  client.destroy() // 关闭连接
})
// 发生错误时触发。 'close' 事件将在此事件之后直接调用。
client.on('error', (err) => {
    
    
  console.log(err)
})

/*********************net.Socket 方法********************************/
// 销毁流并关闭连接。
client.destroy()
// 在给定的套接字上发起连接。
client.connect()
// 获取连接地址信息
client.address()
// 关闭socket,可传入数据,在关闭之前再write一次数据
client.end(data, () => {
    
    
  console.log('连接已关闭')
})
// 暂停读取数据
client.pause()
// 继续读取数据
client.resume()
// 为data事件中的datastream统一设置编码
client.setEncoding('utf8');
// 设置套接字超时事件
client.setTimeout(3000);
// 在套接字上发送数据。 第二个参数指定字符串情况下的编码。 它默认为 UTF8 编码。
client.write(data, (err) => {
    
    
  if (err) return;
  console.log('数据发送成功')
})

Guess you like

Origin blog.csdn.net/woyebuzhidao321/article/details/131494461