TCP/IP protocol stack

The TCP/IP protocol stack, which contains a set of network protocols that make up Internet services, defines a range of standard protocols, from hardware to software, for data transfer between computers.

TCP/IP communications

TCP protocol

Transmission Control Protocol (TCP) is a connection-oriented, reliable, byte stream – based transport layer communication Protocol.

The application layer sends a data stream in 8-bit bytes to the TCP layer, and TCP partitions the data stream into the appropriate message segments. TCP then sends the resulting packet to the IP layer and continues backward.

To prevent packet loss, TCP assigns a sequence number to each packet and ensures that packets sent to the receiving end are received in sequence. The receiver sends an acknowledgement (ACK) of the packet that has been successfully received. If the sender does not receive an acknowledgement within a reasonable round trip delay (RTT), the packet is assumed to have been lost and will be retransmitted. TCP uses a checksum function to check for errors; The checksum is calculated during both sending and receiving to ensure reliable data transmission.

TCP Communication Process

The APPLICATION program based on TCP protocol is divided into two parts: server and client. The working sequence of the two is:

(1) Start to listen to the server application bound to the specific port of the specific host address, listen to the client request; (2) Establish the connection the client application initiates the connection to the server application, and establishes the connection after three handshakes; (3) Data transmission parties use the Socket Socket ports created when the connection is created for data reading and writing; (4) Disconnection Communication ends, one party initiates a disconnection message, and after four waves, the connection is officially disconnected.

TCP three-way handshake

TCP uses a “three-way handshake” to establish a client-server connection. The specific process is as follows:









TCP waved four times


















The Socket communication

After establishing a connection, the server and client in a TCP application create a pair of connected Socket objects, which are used to write and read data from each other.





Net module

Node.js provides THE NET module to realize connection-oriented TCP data communication, which can be used to create TCP server applications and client applications.

class:net.Server TCP Server Object
class:net.Socket Communication socket object
net.connect( ) Connects to the specified TCP server
net.createServer( ) Creating a TCP Server
net.isIP( ) Check whether the parameter string is an IP address
net.isIPv4( ) Check whether the parameter string is an IPv4 address
net.isIPv6( ) Check whether the parameter string is an IPv6 address

Net. The Server object

server.listen( ) Listens for specified ports and addresses
server.unref( ) Exit the server if no more clients are connected
server.ref( ) Canceling the server exit
server.listening Whether the server is in the listening state
server.maxConnections Sets the maximum number of connections that the server can hold
server.getConnections( ) Gets the number of current client connections
server.close( ) Keep existing connections and reject new ones
server.address( ) Returns a server port and address description object

Net.server object events

Event: listening Start listening port
Event: the connection Client connection received. Procedure
Event: the close Server shutdown event; Note: This event will not fire as long as there are client connections
Event: the error Server running error, such as listening port is occupied

Net. The Socket object

socket.remoteAddress The remote address
socket.remotePort Remote port
socket.localAddress Local address
socket.localPort Local port
socket.write Write the data
The socket end () End write, enter the “half connection” state
Socket. Destroy () In the event of an error, destroy the socket
socket.pause( ) Pauses data reception and stores it temporarily in the buffer
Socket. Resume () Continue data reception

Net. Socket object event

Event: the connect Connecting to the server
Event: the data Read data
Event: drain The output buffer is empty
Event: the error Read/write error
Event: the close Fully closed
Event: the end The peer party has sent a Fin packet

Creating a TCP Server

const net=require('net');
var server=net.createServer({
	allowHalfOpen:false.// Whether to allow half-connections. Default is false
  pauseOnConnect:false// Whether to suspend the Socket once the connection is established. The default value is false
},(socket)=>{	// Connect listener
  console.log("Received a client connection!")
  socket.on("data",(data)=>{	// Data is read
  	console.log("Read client data: %s",data)
  })
  socket.write('hello\r\n');
  socket.on('end', () = > {console.log("Connection disconnected!"); })}); server.on('error',(err)=>{
	throw err;
})
server.listen('8000', () = > {console.log('Listening on port 8000... ')})Copy the code

Connect requests can be processed using the createServer callback described above, or you can bind a listener function to the server to listen for the connect connection to be established before processing:

const net=require('net');
var server=net.createServer();// If the default configuration parameters do not need to be modified, you can omit them
server.on('connection',(socket)=>{
  server.getConnections((err,count) = >{
        if(err) throw err;
        console.log("Number of client requests being processed by the server: %d!",count)
  })
	console.log("Received a client connection request...");
})
server.on('error',(err)=>{
	throw err;
})
server.listen('8000', () = > {console.log('Listening on port 8000... ')})// Listening on port 8000...
// Received a client connection!
// The number of client requests being processed by the server is: 1!
Copy the code

Suppose we only allow the TCP server to connect to a maximum of 2 requests:

const net=require('net');
var server=net.createServer();
server.setMaxListeners=2;		// Set the maximum number of connections the server can hold
server.on('connection',(socket)=>{
    server.getConnections((err,count) = >{
        if(err) throw err;
        console.log("Number of client requests being processed by the server: %d!",count)
    })
    console.log("Received a client connection request...");
})
server.on('error',(err)=>{
    throw err;
})
server.listen('8000', () = > {console.log('Listening on port 8000... ')})Copy the code

The first connection and the second connection request were successful, but the third connection request could not be connected.

We can also determine the number of connections and shut down the server when the number of connections reaches 3 or more:

const net=require('net');
var server=net.createServer();// If the default configuration parameters do not need to be modified, you can omit them
server.on('connection',(socket)=>{
    server.getConnections((err,count) = >{
        if(err) throw err;
        console.log("Number of client requests being processed by the server: %d!",count);
        if(count>2){ server.close(); }})console.log("Received a client connection request...");
})
server.on('error',(err)=>{
    throw err;
})
server.listen('8000', () = > {console.log('Listening on port 8000... ')})Copy the code

Sockte object attributes:

const net=require('net');
var server=net.createServer();// If the default configuration parameters do not need to be modified, you can omit them
server.on('connection',(serverSocket)=>{
    console.log("Received a client connection request...");
    console.log("Server port: %s",serverSocket.localPort);
    console.log("Server IP address: %s",serverSocket.localAddress);
    console.log("Client port: %s",serverSocket.remotePort);
    console.log("Client IP address: %s",serverSocket.remoteAddress);
})
server.listen('8000', () = > {console.log('Listening on port 8000... ')})// Listening on port 8000...
// Received a client connection request...
// Server port: 8000
// Server IP address :: FFFF :127.0.0.1
// Client port: 49345
// Client IP address :: FFFF :127.0.0.1
Copy the code

Receiving and responding to messages sent by clients:

const net=require('net');
var server=net.createServer();// If the default configuration parameters do not need to be modified, you can omit them
server.on('connection',(serverSocket)=>{
    console.log("Received a client connection request...");
    console.log("Server port: %s",serverSocket.localPort);
    console.log("Server IP address: %s",serverSocket.localAddress);
    console.log("Client port: %s",serverSocket.remotePort);
    console.log("Client IP address: %s",serverSocket.remoteAddress);
    serverSocket.on("data",(data)=>{The message sent from the client to the server is received
        console.log("Received client message: %s",data);
      	serverSocket.write("Server receives data:"+data);// The server sends a message to the client
    })
})
server.listen('8000', () = > {console.log('Listening on port 8000... ')})// Listening on port 8000...
// Received a client connection request...
// Server port: 8000
// Server IP address :: FFFF :127.0.0.1
// Client port: 49381
// Client IP address :: FFFF :127.0.0.1
// Received client message: a
// Received client message: b
// Received client message: c
// Received client message: d
Copy the code

Example Creating a TCP client

const net =require("net");

var clientSocket=net.connect(8000.'127.0.0.1', () = > {// Connect listener
    clientSocket.write("world!");
    console.log("Server port: %s",clientSocket.remotePort);
    console.log("Server IP address: %s",clientSocket.remoteAddress);
    console.log("Client port: %s",clientSocket.localPort);
    console.log("Client IP address: %s",clientSocket.localAddress);// Write data to the server
})
clientSocket.on('data',(data)=>{// Read data
    console.log(data.toString());
    clientSocket.end();	// Disconnect actively
})
clientSocket.on('end', () = > {// Sending the FIN packet is complete
    console.log("Both parties are in semi-connection!")}); clientSocket.on('close', () = > {// Disconnect completely
    console.log("Connection completely closed!")});// Server port: 8000
// Server IP address: 127.0.0.1
// Client port: 49469
// Client IP address: 127.0.0.1
//response-world!
// Both parties enter the semi-connected state!
// Connection disconnected!
Copy the code