node net module

node net module

network communication support node UDPand TCPtwo transport protocols;

We are concerned today TCP. (TCP protocol module in the node of the net)

TCP

An overview of what TCP(network transport protocols)

  • It supports connection-oriented transport service
  • Supports byte stream transport
  • Support for full-duplex
  • It supports multiple concurrent TCP connections
  • Supports reliable transmission services

It supports connection-oriented transport service

End of transmission: both the program identified by the port number of
the application using the TCP transport prior to data is required 3次握手, to ensure the reliability of communication between programs;

TCP reason to do so, because the IP protocol is a connectionless unreliable; Agreement in IP communications up to ensure
reliability, it can only do it by yourself so that the TCP protocol;

Supports byte stream transport

Stream (stream): corresponds to a pipe, from one end into what, from the other end may be taken out as it is; it describes a loss does not occur, and the data transfer process is repeated scrambled.

Applications and TCP protocols of each interaction 数据长度可能都不相同. However, the TCP protocol is the data submitted by the application considered as
a series of unstructured 字节流. Therefore, the receiving end of application data bytes starting with the end position must be determined by the program itself.

In order to support the transmission of a byte stream, the transmitting end and the receiving end are required to use 缓存 cache; (the data will be verified later event)

Why not send it directly?
Certainly not ah! Would you like your character to enter a client sends a request, it would be too wasteful!

TCP packet length is fixed length of 20 ~ 60 B 20B, options and padding 40B

Support for full-duplex

Full-duplex: the transmitting end and the receiving end can communicate with each other

TCPProtocol allows both the communication application can transmit data at any time.
Since both sides have sent and received 缓冲区;

The sender sends the data to the TCP sender buffer, but will not be sent immediately; timing is controlled by sending TCP;
and after receiving the termination by the data, the data put into the buffer; read by the high level application .

It supports multiple concurrent TCP connections

TCPProtocol supports simultaneous multiple connections it is no doubt;.
, Especially at the receiving end (server)

Supports reliable transmission services

TCP is a reliable transport service protocol that uses acknowledgment mechanism to check whether the data safety and integrity of reach, and provide congestion control function;.
Rely mainly on the sending and receiving of data, data tracking, acknowledgment and retransmission;

Socket

Socket (Socket) is an abstraction layer, the application can send or receive data through it, it can be the same as file open, close, and write operations. Sockets allow an application I / O into the network, and communicate with other applications in the network. Network socket is a combination of IP addresses and ports.

The above is taken from Baidu Encyclopedia;
there is a very good article on speaking socket Jane books

https://www.jianshu.com/p/066d99da7cbd

Of course, Socket nodejs is affirmative in some encapsulation;

Substantially below a node socket flowchart about the event;
wherein the lack of events and lookup timeout; (FIG top a thousand words)

Here Insert Picture Description

ts file that we can provide through vs code, see the Socket property

Allocating two buffers, input buffer and output buffer.

// 写入而缓冲的字符数
readonly bufferSize: number;
// 接收的字节数量
readonly bytesRead: number;
// 发送的字节数量
readonly bytesWritten: number;
// 它将保持为真,直到 socket 连接,然后设置为 false 并触发 'connect' 事件
readonly connecting: boolean;
readonly destroyed: boolean;
readonly localAddress: string;
readonly localPort: number;
// 三元组
readonly remoteAddress?: string;
// 远程 IP 协议。'IPv4' 或 'IPv6'
readonly remoteFamily?: string;
readonly remotePort?: number;

Socket inheritance Streamstream
Stream is what, in terms of this expansion is complicated, involving knowledge IO area.
Later it would add up.

You can see links to articles about it.

https://www.runoob.com/nodejs/nodejs-stream.html

Server

Socket client and server have different functions.

The server will listen listen requesting client;

From api level, we can also look out.

// net 模块
function createServer(connectionListener ? : (socket: Socket) => void): Server;

function createServer(options ? : {
    allowHalfOpen ? : boolean,
    pauseOnConnect ? : boolean
}, connectionListener ? : (socket: Socket) => void): Server;

function createConnection(options: NetConnectOpts, connectionListener ? : () => void): Socket;

function createConnection(port: number, host ? : string, connectionListener ? : () => void): Socket;

function createConnection(path: string, connectionListener ? : () => void): Socket;

Create a Connectionis to create a Socket
create a Serverwhich is also a need to pass Socketin.

Because, TCP this one is transmitted through the socket.

We can look at what Server

 class Server extends events.EventEmitter {
     constructor(connectionListener ? : (socket: Socket) => void);
     constructor(options ? : {
         allowHalfOpen ? : boolean,
         pauseOnConnect ? : boolean
     }, connectionListener ? : (socket: Socket) => void);
     // 省去以一些方法
 }

Underlying processing node on the network is through the bottom do.
Then we have to look at with the deep. Here not carried out.

node will help us deal with that when the request to the network, and will trigger a response in the event is over, will trigger events.
We deal with content like.

Of course, if you have the energy you can also take a look node source.

A request process

Comments of the code in great detail

# 要先启动server才行
node server.js

node client

server

const net = require('net');
let count = 1;

/**
 * 创建一个 server 用于监听client的请求
 * 里面传入的是 connection的监听器,处理conneciton 事件
 * 
 */
const server = net.createServer((clientSocket) => {
    console.log(`客户端已连接,接受到ip :${clientSocket.remoteAddress}  port: ${clientSocket.remotePort} 的socket`)

    // 当有数据传输进来时; data的触发因为有缓存和网络的原因,不一定会触发几次
    clientSocket.on('data', function (buffer) {
        console.log('data事件触发 No : ' + count)
        count++
        console.log('传输的数据 : ' + buffer.toString())
    })

    clientSocket.write('来自server的信息: HELLO CLIENT! ');

    // 可读流 -> 可写流 (socket是Duplex )
    // 这样会把从客户端拿到的data ,再返回给客户端
    // socket.pipe(socket); 

    clientSocket.on('end', () => {
        console.log('client 调用了end');
    });
});


console.log('-----------调用listen之前------------')
// 此时listeing = false 说明还未监听
// 不要在 'listening' 事件触发之前调用 server.address()
// 调用了也没有用 输出null
console.log('server.listening: ' + server.listening)
console.log('server.address(): ' + server.address())

// 指定端口,监听成功后,会调用回调 和下面的listening相同
server.listen(8124, () => {
    // 
    console.log('server.listen(8123) ');
});

console.log('-----------调用listen之后------------')
console.log('server.listening: ' + server.listening)
console.log('server.address(): ' + JSON.stringify(server.address()))

// 监听成功后,会调用; 和server.listen()的回调属于同一个事件
server.on('listening', () => {
    console.log(`server.on('listening',()=>{} `);
})

// 当出错的时候调用,如果没有处理node就崩了
server.on('error', (err) => {
    throw err;
});

// 当 server 关闭的时候触发。 如果有连接存在,直到所有的连接结束才会触发这个事件。
server.on('close', () => {
    console.log(`server.on('close')`)
})


// 当有一个新连接到来的时候,触发
server.on('connection', socket => {
    console.log(`server.on('connection')`)
})

client

const net = require('net');

/**
 * Socket 是全双工的,也就意味着,数据可以相互传递
 */

// 指定port 要和server listen的一致
// 回调是 connnection的事件
const clientSocket = net.createConnection({ port: 8124 }, () => {
  // 连接到 server端之后
  console.log('------已连接到服务器-----');
  clientSocket.write('来自clien的信息: 你好世界!');

  // 这里循环输出了3次,但是只触发了一次事件
  for (let i = 0; i < 3; i++) {
    clientSocket.write('i = ' + i)
  }

  // 这里调用end 会触发
  clientSocket.end()
});

/**
 * events.EventEmitter
 *   1. close 关闭连接
 *   2. connect 连接
 *   3. data 数据
 *   4. drain 写入缓冲区变为空时触发。可以用来做上传节流
 *   5. end data传输结束时
 *   6. error 出现错误
 *   7. lookup 在找到主机之后创建连接之前触发。不可用于 Unix socket。
 *   8. timeout 超时
 *  我们主要看 connect ,data ,end ,close
 */

clientSocket.on('data', (data) => {
  console.log('data : ' + data.toString());
});

clientSocket.on('end', () => {
  console.log('已从服务器断开');
});

Reference Documents

  • Wu Gongyi computer network Tsinghua University Press
  • nodejs official website API net
  • Baidu Encyclopedia Socket
Published 92 original articles · won praise 18 · views 60000 +

Guess you like

Origin blog.csdn.net/qq_34120430/article/details/104331968