当前位置:网站首页>Transport layer UDP & TCP
Transport layer UDP & TCP
2022-06-24 21:43:00 【Programming rookie】
Catalog
- Long short connection
- Talk about port number again
- UDP
- TCP
- TCP Form of agreement
- tcp Confirmation response mechanism
- Over time retransmission
- Connection management mechanism
- The sliding window
- flow control
- Congestion control
- Delay response
- Take a reply
- tcp Sticking problem
- tcp Abnormal situation
- Listen Second parameter of
- be based on TCP Application layer protocol
Long short connection
- A short connection is when a connection is established , Send it once request, Receive once response The connection is disconnected .
- httlp/1.0 Short connections are used . When we need to initiate many times at once request when , Establishing a connection , Destroying the connection becomes the main contradiction , Need to waste a lot of resources .
- So there is a long connection , In a certain amount of time , You only need to make one connection , To receive and send data .Connection: keep-alive.
Talk about port number again
- The port number is used to uniquely identify the process communicating on a host , stay tcp Used in the agreement “ Source ip”、“ Source port ”、“ Purpose IP”、“ Destination port ”、“ Agreement No ” Such a five tuple identifies a communication .
- Open the browser , Different web pages will be bound with different port numbers , And then access different data .A Web page visit Baidu , that B The web page will not display Baidu .
- We come to a conclusion , A process can bind multiple port numbers , But a port number can only be bound to one process . Because the port number is used to identify the unique process , If you can bind multiple processes , The port number is meaningless .
1, Port number range division
- The port number has 16 position , At most 65536 Port number .
- commonly 0 To 1023 Port number is a well-known port number , Some services are bound by default , If HTTP,HTTPS,DNS,SSH, So the operating system does not allow users to bind .
- 1024 - 65535: Port number dynamically assigned by the operating system . The port number of the client program , It is allocated from this range by the operating system .
Some well-known port numbers :
- http:80
- https:443
- ssh : 22
- ftp : 21
- telnet : 23
Related instructions
- View well-known port number
cat /etc/services
- Check the network status (*****)
netstat
n: Reject alias , Can display all the numbers into numbers .
l: List all in listen Service status
p: Show the name of the program that established the relevant link
t: Display only tcp Related options
u: Display only udp Related options
a: Show... In all connections Socket.
- View the process of the server id
pidof Name of the server
UDP
User datagram protocol (udp) Is an important protocol working in the transport layer ,UDP Provides an application with a way to send encapsulation without establishing a connection IP The packet approach .
UDP Form of agreement

/******** UDP Header source code **************/
/************ come from linux kernel 3.0.4 *****************/
struct udphdr {
//udp header
__be16 source; // Source port number ,__be16 Express 16 position
__be16 dest; // Destination port number
__be16 len; //16 position udp length
__sum16 check; //16 Bit checksums
};
How to separate the header from the payload ?
- UDP The header of is a fixed length header , Its header is only 8 byte , Just read 8 The length of bytes is OK .
16 Bit source port number and 16 Bit destination port number :
- All agreements should solve the problem of distribution . and UDP The solution is through the port number . The destination port number marks the process that the message should be delivered . The source port number is used to reply to data .
16 position UDP length :
- We have separated the header , But how do we determine the length of the payload ?
- 16 position UDP Length is the payload + Number of bytes in the header , We just need to subtract... From this data 8, That is, the length of the payload .
- Because of this 16 Bit marks a UDP The length of the message , So every time UDP The maximum payload that a message can send is 2^16 - 8 byte , It's a very small number .
- So how to make the data too large , We need to manually subcontract several times , Then splice them at the receiving end .
16 position UDP The checksum
- UDP It's an unreliable protocol , Once the checksum detects a problem with the data , Discard immediately , No matter what the other problems are .
UDP Characteristics
- There is no connection : Get the other party's ip And port number , No connection needed .
- unreliable : Nothing , Discard directly in case of error .
- For datagram : Every time you send or read data, there are obvious boundaries . For example, I send 100 Bytes , You either don't read , To read, read 100 Bytes , There is no read only 10 In the case of bytes .
other :
- Compared with tcp,UDP It's faster and simpler .
- udp It's full duplex , It can receive and send data at the same time .
- udp No send buffer , But there is a receive buffer .
udp The buffer :
- udp No send buffer , Because it receives the upper datagram , Directly add the message and it will be transmitted to the next layer , There is no need to do any extra action , Because it doesn't consider reliability .
- udp There's a receive buffer , If too much data is sent , The receive buffer will also be full . If the buffer is full , Redundant udp The message is directly discarded ( you 're right , That's the violence .). and udp The receive buffer of is not guaranteed udp Order of message . That is, you send 1,2,3, Maybe it's just 3,2,1.
be based on UDP Application layer protocol
- NFS: Network file system
- TFTP: Simple file transfer protocol
- DHCP: Dynamic Host Configuration Protocol
- BOOTP: Boot protocol ( For diskless device startup )
- DNS: Domain name resolution protocol
TCP
TCP It's called transmission control protocol , The main function is to control the data transmission in detail .
TCP Form of agreement

- tcp The header is the same , The problem of distribution and unpacking needs to be solved .
- First line 4 Source port number of bytes , And the destination port number determine which process the message is delivered to .
- The serial number identifies the order of the data .
- Confirmation serial number is the confirmation of data , Generally, it is serial number +1.( I'll talk about it later )
- The data offset identifies tcp The length of the header , Its unit is 4 byte , That is to say, if the data offset is x, Then the header length is x*4.
6 Identification bits :
- In fact, in the source code 8 Identification bits , But the last two follow IP of , Not at this time .
- FIN(finish): Identification bit for terminating the connection , stay 4 Used in the message of the second wave .
- SYN(synchronization, Sync ) : The identification bit for establishing the connection .
- RST: There was a problem establishing the connection , reestablish connection .3 When shaking hands for the first time , Client receives server's ACK+SYN It is considered that the connection is established , It will send data . At this point, if the server does not receive a message from the client ACK, Instead, I received data , The server will realize ACK The loss of , So that's the setup RST Identification bit .
- PSH: Urge your output buffer to send data quickly , Urge the receiving buffer of the other party to deliver the data to the upper layer .
- ACK: Confirmation character , To confirm the receipt of a message .
- URG: When there is an emergency message ,URG Set up , Use with emergency pointer .
Reserved items :
- tcp The header is not fixed , Because there is a reserved option after the header, which can be left unchecked . Specific functions are not discussed .
16 Bit window :
- tcp There is a receive buffer . But the buffer must have a size . If the sender keeps sending a lot of data to the server , Then the buffer must be filled , Then send the data , There will be packet loss .
- Therefore, we hope that the sender can obtain the acceptance ability of the receiver , If the other person's receptivity is weak , Then send it slowly .
- 16 Bit window is sending tcp The message will be filled , Filled with ( The sender ) Own unused receive buffer size . Pay attention to is , stay tcp3 When shaking hands for the first time , The windows of both sides will be “ negotiation ”. This is called flow control .
actually ,tcp There is a timeout retransmission mechanism , You may ask , Since there is a retransmission mechanism , Just retransmit , Why flow control ?
- It is unhealthy to use timeout retransmission to deal with packet loss ! Network resources are limited , Your retransmission will certainly waste resources , So in order to save Internet resources , Flow control .
Pointer to an emergency :
- When an emergency message comes , We need to deal with the emergency message first , And the emergency message will be put into tcp The front of the message . The emergency pointer points to the last byte of the emergency message +1, Used to identify the length of emergency data .
Inspection and :
- How to determine whether some information is lost during data transmission ?
- The sender fills in , CRC check . The receiver fails the verification , They think there is something wrong with the data . The test here not only includes TCP The first one , Also contains TCP Data section .
tcp Is the length of data specified ?
- No, . because tcp It's byte stream oriented . Random reading at one time .
/************tcp header Source code **************/
/****************linux kernel 3.0.4*****************/
struct tcphdr {
//tcp header
__be16 source; // Source port number
__be16 dest; // Destination port number
__be32 seq; //32 A serial number
__be32 ack_seq; //32 Bit confirmation serial number
#if defined(__LITTLE_ENDIAN_BITFIELD) // Small end storage
__u16 res1:4,
doff:4,
fin:1, // Finish, Terminate connection
syn:1, // Synchronization( Sync ), Establishing a connection
rst:1, // Reset, There was a problem establishing the connection , Rebuild
psh:1, // Push, Push the sender to send data quickly , Promote the receiving party to quickly distribute upward .
ack:1, // Acknowledge character, Acknowledge receipt of
urg:1, // Urgent, Emergency position
ece:1,
cwr:1;
#elif defined(__BIG_ENDIAN_BITFIELD) // Big end
__u16 doff:4,
res1:4,
cwr:1,
ece:1,
urg:1,
ack:1,
psh:1,
rst:1,
syn:1,
fin:1;
#else
#error "Adjust your <asm/byteorder.h> defines"
#endif
__be16 window; // The sliding window
__sum16 check; // The checksum
__be16 urg_ptr;// Pointer to an emergency
};
tcp Confirmation response mechanism
reliability : As long as you receive a response from the other side , It is considered that the previous data has been received by the other party !!
chestnuts :
- A Host to B Host sends a hello_B,A How does the host confirm B The host received ? received B Reply from the host , I got it. . however , I got it. This sentence itself is data ,B How can the host ensure that I receive this sentence A Received ?
- You will find a problem : In Internet data transmission , There is no absolute reliability , Because you can never be sure whether the last message was received by the other party .
- So we only have relative reliability , So we don't need to answer the answer , I.e. no need for ACK Conduct ACK.
tcp Based on acknowledgement response mechanism :
- tcp For reliable transmission , The transmission is a byte stream . therefore , about tcp The agreement needs to achieve the following two points :① Ensure that the receiving end successfully receives data ② Ensure the order of the data received by the receiving end .
- Even if the data is sent in the correct order , Because of the complexity of the network , The receiving party may not receive in order . So you need to sort .
Confirmation response mechanism : Every time the sender sends a data , The receiver will send an acknowledgement signal to the sender , Indicate that you have received the data , So as to ensure that the receiving end successfully receives data .
that tcp How to ensure that data arrives in order ?
- tcp Each byte of data in the send buffer is labeled , When sending, fill the sequence number of the last byte into tcp The message 16 Bit sequence number , Represents the sequence of data sent by the sender . The receiving party only needs to follow 16 Bit sequence number sorting can ensure the order of data .
- and tcp One more 16 Bit confirmation number , Every time data is received ,tcp It is necessary to send a confirmation message to the other party , Of this acknowledgement message ack Will be filled in , and 16 The confirmation sequence number of bits is the sequence number of data +1, Indicates that you should start sending data from the confirmation sequence number , Previous data has been received . Confirm the serial number by serial number and ,tcp The confirmation and response mechanism is perfectly implemented .
Two questions :
- Why should there be a serial number ?
We need serial numbers to ensure the order of reception .
- Why two sets of serial numbers ?
because tcp It's full duplex , Can send and receive data at the same time .
Over time retransmission
tcp The protocol ensures reliable data transmission , You also need to make sure that the lost data can be re sent . If the data is not received from the other party within a period of time after sending ACK, Think of data loss , Need to retransmit , This is the retransmission timeout mechanism .
What situations require overtime retransmission ?
Due to network congestion or other network reasons , Data is lost directly in the network .

It could also be a host B Reply ACK when ,ACK Lost on the network .
- Whether it is the direct loss of data or the other party's ACK The loss of , This is for A The host is the same , Because the confirmation response mechanism stipulates A The host must receive B The host ACK To confirm that the data is normally received .
- There are two more problems to be solved :
- Since it is a timeout retransmission , So how to set the time ?
- After retransmission , It is very likely to lead to data duplication , How to go heavy ?
analysis :
- The time must not be set too short , Otherwise, a lot of duplicate data will be transmitted , Waste network resources .
- It can't be too long , Because it is too long, the transmission efficiency decreases .
- TCP In order to ensure high-performance communication in any case , Will dynamically calculate this time .
- stay linux The time-out period is in 500ms For a unit , The time for each overtime retransmission is 500ms Integer multiple .
- If the retransmission is still not answered , Will wait for 500*2ms And then retransmission ,
- If you still can't get an answer, you are waiting 4*500ms retransmission , Exponential growth , And so on .
- When accumulated to a certain number of times ,tcp It will be considered that the opposite end or network is abnormal , Direct force disconnect .
duplicate removal :
- tcp There is... In the message 16 A serial number , Another function of serial number is to remove duplication . Keep one copy of the message with the same serial number .
http Send a request, Then receive a response, Does this correspond to tcp A confirmation response of ?
- Not at all . Upper layer request and response There is no one-to-one relationship with the underlying acknowledgement and response mechanism .
- send Just copy the upper data to the kernel . How to send it , Confirm that the reply is the communication details in several times , No http Concerned .
Example :
- School orders 1 Ten thousand books , Then the publisher asked SF express to deliver the 10000 books . SF can choose one shipment 500 Ben , Or one shipment 400 Ben , Finally to the destination , Integrating into 1 Ten thousand copies were distributed to the school .
Connection management mechanism
tcp need 3 Establish a connection with a handshake ,4 One wave to disconnect .
How to understand connection ?
- The connection itself has a cost , On the one hand, space , One is time .
Three handshakes :
- Generally, the client initiates a connection request .
- The client sends a connection request to the server , With SYN Message of , And set yourself to SYN_SENT The state of , Block waiting .
- The server receives SYN After the message , send out ACK+SYN Message to client , Indicates that the server has received SYN message , And require the establishment of a connection between the server and the client . And set yourself to SYN_RCVD state .
- The client received ACK+SYN after , Send... To the server immediately ACK message , In the client's view , Connection established , namely ESTABLISHED.
- When the server receives the last ACK when , The server-side connection is also established .
Why three handshakes to establish a connection ? Not once or twice ? Four handshakes ?
- Because you need to synchronize .tcp Serial number negotiation is required when establishing a connection . hypothesis A The client side. ,B Is the server .A to B Send with SYN Message of , Randomly select a sequence number in the send buffer seq = x, Then send it to the server .tcp Specified with SYN The message of is not allowed to carry data , But it has a serial number .B received SYN After the message , Set the confirmation number to ack_seq = x + 1, Then set the SYN and ACK Identification bit . tcp Regulations ACK Can carry data , If you don't carry , No serial number is consumed . Randomly select a sequence number in your own buffer seq = y, Send to client . When the client receives , To his own ack_seq = y+1, Connection established .
- Need to verify full duplex .tcp3 A handshake can confirm tcp Two way communication channels are available . Both the server and the client perform a receiving and sending process .
- If it's two handshakes , It may lead to misjudgment of the server . Let's take a look at the normal situation of two connections :A send out SYN Request to B,B send out ACK, Then establish a connection . If SYN Request lost , Then according to the retransmission mechanism ,A Will be sent again SYN message , The connection is now established , No problem .
- however , If SYN There is no loss , Because the network problem is blocking the network . From the client's point of view , The server did not receive SYN, It will be retransmitted , The connection is now established , After communication , Connection release . however , The last connection blocked in the network will also be B receive ,B It's going to make a connection , towards A send out ACK. however A There was no initiative at all SYN,A You can ignore this ACK, As a result, the resources of the server are wasted .
- A handshake does not verify the dual full-service channel at all . and 2 This communication is vulnerable to SYN The flood hit , Crazy use of server resources .
- So why not shake hands four times , Five handshakes , Or more times ? Because in the network , There is no absolute reliability , We don't need to be right ACK Conduct ACK.3 A handshake is the least expensive ,5 Time 7 Time ... Shake hands with 3 The effect is the same , More handshakes will only waste resources .
Are you sure to succeed in shaking hands three times ?
- not always . But don't worry . The loss of the first two handshakes has no effect . Because of the loss of the previous two messages , Neither the server nor the client has established a good connection . There is no waste of resources .
- Even if the third message is lost , The client has established a connection . The client will send data , But the server has not established a good connection , The server will send a message with RST Message of , Tell the client , You need to resend the second connection . Once the time-out retransmission has not been completed for several times , Then the connection will be forcibly disconnected .
Four waves
- tcp Connection release of needs to be done 4 Second wave . We assume that A Is the server ,B The client side. .
- A Active disconnection , towards B Send connection release message , Set up FIN by 1, Active shut down TCP Connect , Not sending data . Be careful , Not sending data here means that the application layer no longer sends data , It does not refer to communication details such as the transport layer . Its serial number seq = u,u yes A Transferred data +1. here A Get into FIN_WAIT_1.tcp Regulations FIN Even if the message does not carry data , Also consume a sequence number .
- B received A Of FIN After the message , Send a confirmation , Confirm the serial number ack_seq = u+1, Serial number is v,v be equal to B Serial number of data sent +1.B Get into CLOSE_WAIT state . here tcp It's half closed ,A Can't send data anymore , But if B Continue sending data ,A Still want to receive .
- A received B After the confirmation of , To get into FIN_WAIT_2 state , wait for B issue FIN message .
- if B No data to send ,B It will send FIN message . take FIN The identification bit is set to 1, Set the sequence number to w( Why not v? Because in B Not sent FIN period ,B You can also continue to send data , One-way communication .), meanwhile B The last confirmation number must also be sent repeatedly ack_seq = u + 1. here B Get into LAST_ACK state .
- A Upon receipt of B Of FIN After the message , This must be confirmed . In the confirmation message ACK The identification bit is set to 1,seq = u + 1(FIN Consume a serial number ), ack_seq = w + 1. then A Get into TIME_WAIT state . Be careful , here tcp The connection has not been released yet !!! until TIME_WAIT Time set 2*MSL Only after ,A Only enter CLOSED state .
- B Upon receipt of ACK after , Also enter CLOSED state .
CLOSE_WAIT && TIME_WAIT
- CLOSE_WAIT: When the server receives the FIN, Send out ACK when , The server will become CLOSE_WAIT state . here , If the server does not continue to close the corresponding socket ( Third wave ), Then the connection will get stuck CLOSE_WAIT state , Waste server resources . So we should avoid this situation .
- TIME_WAIT: The party who actively disconnects ( you 're right , The server may also be in this state !), Send out at the end ACK when , Need to wait .
- significance :1, the last one ACK May be lost in the network , If ACK The loss of , that B The connection cannot be released . So when B Wait for a while , No waiting ACK when ,B A timeout retransmission will occur FIN, If A already CLOSED, Then you can't receive ACK, As a result, the resources of the server have been wasted . although , Finally, several time-out retransmissions are made B Will be released , But this is an unhealthy practice !!! therefore , We need to A wait a second , This time is 2*MSL( Maximum segment life ), That is, the longest time that data is received at one time .
- 2, Wait for historical data to dissipate on the network .A After disconnection ,B You can still send data to A. There may be B The data sent is blocked in the network , But at this time A The connection has been destroyed , Can't receive B The data of . therefore , need A Wait for the data to dissipate in the network .
- TIME_WAIT: 2*MSL,2 Times the maximum transfer time .
Why 4 Second wave ?
- Because connection is the business of both parties , Mutual requests and confirmations are required .
TIME_WAIT The embodiment of state :
- Open a server , Then close it immediately . When we connect it through the same port number again , Failed to connect , Because the server is in TIME_WAIT state , The bottom layer has not been disconnected .
- But the server needs to be restarted immediately after it hangs up , Otherwise, the losses will be heavy . We need to solve this problem . Use setsockopt Function for port multiplexing .

Grab the bag
tcpdump -i any -nn tcp port 8080
The sliding window
- To compensate for the shortcomings of the acknowledgement response mechanism . The acknowledgement mechanism requires that we receive ACK To determine the reliability of the information , But above we only confirm one piece of data at a time , It's serial , Although this method ensures high reliability of data , But it's a little inefficient .
- Sliding window is a very efficient way to sacrifice some reliability .
- The sliding window is part of the send buffer . Think of the send buffer as a ring queue .


Sliding windows allow you to send a batch of data at a time , In the process of transmission, it can be sent directly without waiting for the response of a certain data . The size of the sliding window is the maximum value sent ( You can also send data smaller than the sliding window !).
Pictured above , A red box is a sliding window ,28-31 No. data has been sent , and 32-33 No. data can also be sent directly , Don't wait for 28-31 The no. ACK. Data that has been sent but not confirmed should not be cleared , In case of overtime retransmission .
The sequence number in the send window is the sequence number allowed to be sent . The larger the sliding window , Then the more efficient . But the sliding window must be smaller than the other side's window size ! Sliding windows are also limited by the size of the congestion window , Explain later .
The data on the left side of the sliding window can be cleared , Because I have received ACK. The data on the right of the leading edge cannot be sent , Because the other party may not have additional space to store this part of data .
The position and size of the sliding window will change ! The sliding window Back edge Can move forward , When the sliding window part data is received ACK. You can also not move , When not received ACK. Backward movement is not allowed . When a sliding window is received ACK when , You have to move forward , because tcp The confirmation will not be revoked . such as 28-31 Data no. , received 30 The no. ACK, Then the back edge of the sliding window will move forward 3 Bytes regardless 28-29 Data no. . The leading edge of a sliding window is usually moved forward , But it's also possible not to move . First, no new confirmation has been received , The size of the other side's window remains the same ; Second, new confirmation has been received , The other side's window is getting smaller .
An important conclusion : The leading edge and trailing edge of the sliding window do not change synchronously !!
The leading edge can also be moved back , But the standard strongly does not recommend !! Because the sliding window may have sent the data , But the front moved back , Identify the data you have sent as data that is not allowed to be sent , This will cause errors .
Describe a sliding window :
- We just need 3 A pointer can describe a sliding window , namely p1,p2,p3.
Packet loss of sliding window :
situation 1,ACK The loss of .

At this point, the sliding window directly ignores , As long as the follow-up ACK received , Just move back .situation 2, Message lost .

- When the packet is really lost , Retransmission is required , This requires that the message sent in the sliding window ACK Make sure his previous data has been received . for example , The sequence of data received by the receiving end is 1~ 1000、5001~ 6000、4001~ 5000, When receiving 5001~ 6000 Data cannot be sent immediately after 6001 Of ACK, We have to wait until 6001 The previous data can only be sent after all the data have arrived .
- When 1001-2000 After the message of is lost , The next few at the receiving end ACK The message will ack_seq Set to 1001, Remind the client 1001-2000 Message number is lost . Once the client receives 3 It's the same ack_seq, Then the client will retransmit this part of the message .
- Because this method is faster than timeout retransmission , be called Fast retransmission .
- At this time, the receiver receives 1001 after , Return again ACK Namely 7001 了 ( because 2001 - 7000) In fact, the receiving end has been Received , Is placed in the receive buffer of the receiving operating system kernel .
With a fast retransmission , Why do I need to retransmit over time ?
When your sliding window is smaller than 3 when , Unable to trigger fast retransmission . and , If all ACK It's all lost , Nor can a fast retransmission be triggered . Therefore, it is necessary to retransmit the information over time . These two methods complement each other .
flow control
- If the sender keeps sending data to the other party , This may cause the receiving buffer of the other party to be full . At this time, if you send again , You may lose packets , Therefore, it is necessary to control the flow according to the capacity of the receiving end .
- stay SYN When the connection is established, window negotiation will be carried out , At this point, the flow control has been carried out .
- If B Unable to receive data , Then you will set your own window to 0, Then send it to A.A When received, it will block and wait .
that , How to know that the other side's window has space ? - A From time to time, a message without data will be sent Window detection message , Used to get the window size of the other party .
- But it is also possible that your window detection message will also be lost , Then you need to retransmit , If the window probe setting time is 1s, But your buffer is 0.1s After that, the window size has been updated , Then the sender needs to wait 0.9s Sending , It will cause a waste of time , So the receiver should also set a Window update notification , When the window is updated , Actively send to the sender , This saves time , Improved efficiency .
- If you don't get data all the time , Then it is the application layer bug.
Congestion control
- If 10000 Several messages need to be retransmitted , That means the network is OK . But if 10000 A message , Yes 9999 Need retransmission , that tcp You will think that the network is in a bad state .
- Without knowing the current network state , Sending a lot of data rashly , It's likely to make things worse . TCP introduce Slow start Mechanism , Start with a small amount of data , Explore the way , Find out the current state of network congestion , And then decide how fast to transmit data ;
- We introduce the concept of congestion window . The congestion window represents The size of the small amount of data used for pathfinding . When you start sending data , The congestion window is defined as 1, For every one received ACK Congestion window +1, Each time when sending data, compare the size of the congestion window with the size of the window fed back by the host , Take the smallest as the actual sending window size .
Slow start :
- In order to avoid more network congestion , We set the blocking window to be very small at first , Then the way to start exponential growth . Slow start does not mean that the blocking window grows slowly , It means that we set the blocking window to be very small at the beginning , This is much slower than putting a lot of data on the network at the beginning .
To prevent the slow start index from growing too fast , When the congestion window increases to a certain extent, it will increase linearly .
Fast retransmission and fast recovery algorithms
- Because congestion control exists , Sometimes a small number of messages are lost , Sending will also reset the congestion window to 1, This will lose efficiency . At this point, we need to quickly retransmit , Quickly inform the sender of the lost message .
- When the sender finds that a small number of messages are lost rather than the network is bad , The sender will execute the fast recovery algorithm , Quickly expand the size of congestion window .
A person's data is drizzled on the Internet , So why congestion control ?
- Congestion control is Multi person control .
- One person's congestion control has little effect on the network , But now almost all processes support tcp service , There is congestion control , So all congestion control works , Will make the network better .
Delay response
When the server receives tcp When the message , You can wait and send ACK, wait a second . Wait for the upper layer to take the data from its own buffer , In this way, your window will become larger , then ACK Give the client a bigger window , This will increase efficiency .
Assume that the receiver buffer is 1M. Once received 500K The data of ; If you answer immediately , The returned window is 500K;
But in fact, the processing speed of the processing end may be very fast , 10ms Put... In 500K Data is consumed from the buffer ;
under these circumstances , The receiving end processing is far from reaching its limit , Even if the window is a little bigger , Can handle it ;If the receiver waits a little while before answering , Such as waiting for 200ms Answer again , Then the window size returned at this time is 1M;
** The greater the window , The greater the network throughput .** We need to make sure that the network is not congested , Try to improve efficiency . But not every packet is delayed , It is usually separated by several bags , Or delay a packet at intervals .
Take a reply
When receiving data from the other party , We often reply to each other . Data to the opposite party at this time ACK You can take a ride , Follow our reply data and deliver it to the other party .
tcp Sticking problem
- A Use tcp The agreement is sent to B Several packets , because tcp Is oriented to a byte stream , that B When delivering to the upper layer , Is it possible to deliver half a package at a time , Or one delivery 1 A half ? This leads to incomplete packets . Our application layer protocol should have the function of actively separating each packet , for example http There is Content-Length:size Key value pair .
tcp Abnormal situation
- A and B Established tcp Connect .
- A Follow B Communicating ,A Host based tcp Process to hang . Because the file life cycle changes with the process , therefore socket Will be closed . At this time, the bottom tcp The connection will send FIN, Just like closing the connection normally .
- Machine restart : As in the case of process termination ( Before restarting , The computer will prompt whether there are still running processes to confirm the shutdown , That is to say, the process will be shut down before restarting ).
- The machine is powered down / The network cable is disconnected : The receiving end thinks that the connection is still , Once the receiver has a write operation , The receiving end finds that the connection is no longer present , It will reset.. Even if there is no write operation , TCP I also have a built-in Life keeping timer , Will regularly ask if the other party is still . If the other person is not there , Will also release the connection . in addition , Some protocols of application layer , There are also some such detection mechanisms . for example HTTP Long connected , They also regularly check each other's status . for example QQ, stay QQ After disconnection , Will also periodically try to reconnect .
Listen Second parameter of
- tcp Connection required , But it is possible that the network resources are full . The server cannot immediately accept Connect . Then you need to connect line up . According to the queued connection status , It can also be divided into the following 2 Kind of :
- Full connection queue : That is, the server and client are in ESTABLISHED State connection . Three handshakes are done .
- Semi connected queues : That is, the server and client are in SYN_SENT and SYN_RECV State connection , Three handshakes were not completed .
- and Listen The second parameter of is the length of the full connection queue . That is, these connections have been completed , But not immediately accept. When the full connection queue is full , The new connection cannot be accessed ESTABLISHED state , Only semi connected queues can be entered .
- The length of the full connection queue is Listen Second parameter of +1( Because the greater than sign is used in the kernel to determine whether it is full , Not the greater than or equal sign ).
be based on TCP Application layer protocol
- HTTP
- HTTPS
- SSH
- Telnet
- FTP
- SMTP
( End of this chapter )
边栏推荐
- 数据链路层 && 一些其他的协议or技术
- Implementation of adjacency table storage array of graph
- Auto. JS to realize automatic unlocking screen
- Interpretation of ebpf sockops code
- Pattern recognition - 0 introduction
- 虚拟机CentOS7中无图形界面安装Oracle(保姆级安装)
- Tdengine can read and write through dataX
- Concepts of kubernetes components
- RFC 793 why to send reset and when to send reset
- Alibaba cloud schedules tasks and automatically releases them
猜你喜欢

EditText 控制软键盘出现 搜索

Please open online PDF carefully

CondaValueError: The target prefix is the base prefix. Aborting.

传输层 udp && tcp

Memcached comprehensive analysis – 2 Understand memcached memory storage

memcached全面剖析–2. 理解memcached的內存存儲

煮茶论英雄!福建省发改委、市营商办领导一行莅临育润大健康事业部交流指导

OSI and tcp/ip model

Memcached comprehensive analysis – 3 Deletion mechanism and development direction of memcached

CondaValueError: The target prefix is the base prefix. Aborting.
随机推荐
Ebpf XDP mount point analysis
Simple analysis of WordPress architecture
Bld3 getting started UI
Dijkstra seeking secondary short circuit (easy to understand)
[cloud native learning notes] learn about kubernetes configuration list yaml file
Docking of arkit and character creator animation curves
[cloud native learning notes] kubernetes practice command
Web project deployment
Php-pdo parameter binding problem
Logical backup: mysqldump vs physical backup: xtrabackup
memcached完全剖析–1. memcached的基础
CondaValueError: The target prefix is the base prefix. Aborting.
Static routing experiment
Tso hardware sharding is a header copy problem
Slider控制Animator动画播放进度
TCP specifies the source port
MySQL optimizes query speed
介绍BootLoader、PM、kernel和系统开机的总体流程
socket(2)
[cloud native learning notes] deploy applications through yaml files