emmmmmmm… TCP As we all know, TCP is a network protocol.

Speaking of network, when I studied computer network in college, I remember the teacher said that network is divided into seven layers, which are the physical layer, data link layer, network layer, transmission layer, session layer, presentation layer and application layer from top to bottom. Here’s a picture:

OSI stands for Open System Interconnection. The International Organization for Standardization (ISO) developed the OSI model, which defines the standards for interconnecting different computers and is the basic framework for designing and describing computer network communication. OSI model divides the work of network communication into seven layers, namely physical layer, data link layer, network layer, transport layer, session layer, presentation layer and application layer

Above is the basic network model composition. Let’s look at the TCP/IP reference model again

TCP/IP is short for Transmission Control Protocol/Network Interconnection Protocol. The early TCP/IP model is a four-layer structure, from the bottom up are the network interface layer, the Internet layer, the transport layer and the application layer. Later, the network interface layer is divided into physical layer and data link layer by referring to the OSI seven-layer reference model, forming a five-layer structure.

We see the TCP/IP network model combining the OSI application layer, presentation layer, and session layer into the application layer. Tcp is actually at the transport layer. The transport layer is a connection-oriented, reliable process-to-process communication protocol. TCP provides the full-duplex service, that is, data can be transmitted in both directions at the same time. TCP combines several bytes into a group, which is called a Segment. Provides an end-to-end connection. The transport layer protocol is TCP, and TCP(TCP) is a reliable and connection-oriented protocol with low transmission efficiency.


Let’s look at the FORMAT of TCP

  • The source port number and the target port number, by which the computer identifies which service to access, such as HTTP service or FTP service, the sender port number is the random port, the target port number determines which program to receive.
  • 32-bit SEQUENCE Number TCP marks packets with sequence numbers so that they can be reassembled at the destination. Assuming that the current sequence number is S and the length of the data sent is L, the sequence number of the next data sent is S + L. When establishing a connection, the computer usually generates a random number as the initial value of the serial number to confirm that the answer number is equal to the serial number of the data that should be received next time. If the serial number of the sender is S and the length of the data sent is L, the acknowledgement number returned by the receiver is also S + L. When the sender receives this acknowledgement, it can be assumed that all previous data at this location has been received normally.
  • Header length: indicates the length of the TCP header, in 4 bytes. If there are no optional fields, then the value here is 5. Indicates that the length of the TCP header is 20 bytes. Control bits TCP connections, transmissions, and disconnections are directed by these six control bits
  • PSH(Push urgency bit) cache will be full, transfer speed immediately
  • RST(reset reset bit) The connection is disconnected and the connection is reconnected
  • URG(Urgent Urgent Bit) Emergency signal
  • An ACK(Acknowledgement) value of 1 indicates the acknowledgement number
  • SYN(synchronous establishing online) Synchronization sequence number

  • This value is set to 1 when TCP establishes a connection
  • The FIN sender completes the bit. The FIN sender sets the value to 1 to indicate that the connection is to be disconnected
  • The window value indicates the number of data segments that can be received locally. The size of this value is variable. When the network is smooth, increase the value of this window to speed up the transmission speed; when the network is unstable, reduce the value of this window to ensure the reliable transmission of network data. It is used for flow control over TCP transmissions
  • Window size: Used to indicate how many 8-bit bytes can be accepted starting with the answer number. If the window size is 0, window probes can be sent.
  • Validation sum: Used for error control, the CALCULATION of the TCP checksum includes the TCP header, data, and other padding bytes. The checksum is calculated by the sender when the TCP data segment is sent, and is checked and calculated again when the destination is reached. If the two checksums are the same, the data is correct. Otherwise, the data is considered corrupted and the receiver discards the data
  • Urgent pointer: valid only when URG(Urgent Urgent) control bit is 1. Indicates that the end of the emergency data is in TCP

  • Location in the data section. Usually used to temporarily break communication (e.g. Ctrl + C).
  • Three-way handshake

    I think everyone knows this thing. So what exactly is a three-way handshake? For example 🌰 let’s say I go to a coffee shop to buy coffee. Then I ask the clerk: Do you have any coffee? Then the clerk told me: Yes. Do you have any money with you? Then I said: I have the money, give me a cup. And then we should give money give money give coffee give coffee

    Let’s look at this example. If say I be client, shop assistant is server. Then I asked the server, can you set up a connection (a handshake)? The server says I can set up a link, can you set up a connection (second handshake)? At this point I reply that I can make a link (three handshakes)…

    emmmmm… Then we two retards happily established a link. Do something stealthily passing things around.

    To visualize the three-way handshake, let’s take a look at this:

    We can see it very clearly. First handshake: Establish a connection. The client sends a connection request, sends a SYN packet, and sets seQ to 0. The client then enters the SYN_SEND state and waits for confirmation from the server. Second handshake: The server receives a SYN packet from the client. The SYN segment needs to be acknowledged, and an ACK packet needs to be sent with ACK set to 1. It also sends a SYN request, setting seq to 0. The server sends all the above information to the client, and the server enters the SYN_RECV state. Third handshake: After receiving ACK and SYN packets from the server, the client acknowledges them, sets ACK to 1 and SEQ to 1, and sends an ACK packet to the server. After the ACK packet is sent, the client and server enter the ESTABLISHED state to complete the TCP three-way handshake.

    Four times to wave

    Let’s take another example 🌰

    If I go to a restaurant, I have to pay when I finish eating. At this time I will call the waiter to pay the bill -> the waiter said do you want to pay -> the waiter said a total of XXXX yuan -> I can leave after the money

    The analogy may not be quite right. But that’s about it. Let’s go straight to the picture

    First wave: The client sends a FIN ACK packet to the server. At this point, the client enters the FIN_WAIT_1 state, which means that the client has no data to send to the server and requests to close the connection.

    Second wave: The server receives the FIN packet from the client and returns an ACK packet to the client. The server enters the CLOSE_WAIT state. After receiving the ACK packet from the server, the client enters the FIN_WAIT_2 state.

    Third wave: The server checks whether any data has not been sent to the client. If yes, the server sends the data to the client and then sends a FIN packet. If no, the server directly sends FIN packets to the client. The server is requested to close the connection and enter the LAST_ACK state.

    Fourth wave: The client receives the FIN packet from the server and sends an ACK packet to the server. Then the client enters the TIME_WAIT state. After receiving the ACK packet from the client, the server closes the connection. At this point, the client waits 2MSL (about 4 minutes?). If no reply is received, the Server is shut down and the client can close the connection.


    Now that we know about the three handshakes and the four waves we might have a few questions

    1. Why do the client and server need a three-way handshake

    A: The three-way handshake is used to ensure that the client and server can send and receive messages properly.

    2. Why do you need four waves?

    A: The purpose of the four waves is to ensure that the data on both sides can be disconnected after being sent.

    3. Why three handshakes and four waves

    A: The server may not shut down immediately after receiving a FIN packet. In this case, the client may send a FIN packet that is disconnected, and the server still has data to transmit. In this case, the connection should not be disconnected immediately.


    TCP(NET module) in NodeJS

    In Node.js, NET module realizes data communication based on TCP

    Let’s look at creating a simple TCP server

    Creating a TCP Serverlet net  = require('net');
    let server = net.createServer(function(socket){
        console.log('Client is linked');
    })
    server.listen('8080'.function(){
        console.log('server is run in 8080');
    })
    Copy the code

    This creates a simple TCP server using NodeJS; Note: The createServer callback has a parameter socket that refers to the socket port object on which the TCP server listens.

    Sets the maximum number of links and the number of links listening to clients

    server.getConnections((err,count) = >{// Get the current number of links
        console.log('Already linked'+count+'One user')}); server.maxConnections =2;// Limit the current maximum number of connections to 2
    Copy the code

    The socket object

    Net. Socket represents a Socket port object, which is a duplex stream (readable and writable)

    address

    Obtain the client address

    let net = require('net');
    let server = net.createServer(function(socket){
       console.log(socket.address())
    });
    server.listen(8080);
    Copy the code

    Results:

    pipe

    let ws = fs.createWriteStream(path.join(__dirname,'./1.txt'));
    
    let server = net.createServer(function(socket){
      socket.pipe(ws,{end:false}); // The second argument keeps the file from closing automatically
      setTimeout(function(){
        ws.end(); // Close the writable stream
        socket.unpipe(ws); // Cancel the pipe
      },15000);
    });
    Copy the code

    We can see that we have created a writable stream, and we can pipe the socket into the writable stream.

    Server and client

    Create a server

    let net = require('net');
    
    let server = net.createServer(function(socket){
      socket.setEncoding('utf8');
      socket.on('data'.function(data){
        console.log(data); // Get the data from the client
      })
      socket.end('Server down');
    });
    server.on('connection'.function(){
      console.log('Client link');
    })
    server.listen(8080);
    Copy the code

    Create a client

    let net = require('net');
    //createConnection the first parameter is the port number you want to connect to the server
    let socket = net.createConnection(8080.function(){
      socket.write('hello'); // Send to the server
      socket.on('data'.function(data){
        console.log(data); // Accept server data
      });
    });
    Copy the code