当前位置:网站首页>TCP Basics
TCP Basics
2022-07-28 10:00:00 【amireux512】
Catalog
Two ,TCP Implementation of reliable communication
1. Three handshakes , Four waves
4, Confirm the response and serial number
6, The sliding window : Cumulative response and flow control
3、 ... and ,TCP Programming steps
One , Basic concepts
1,TCP The concept of
TCP: Transport Control Protocol Transmission control protocol , Is a connection oriented transport layer protocol .
Establish a connection before communicating ==> " Three handshakes "
It can provide high reliability communication ( That is, the data is correct , No data loss , There is no out of order data , No duplication of data )

Two ,TCP Implementation of reliable communication
1. Three handshakes , Four waves
SYN by Marker bit , Express “ Request a new connection ”
Seq(sequence number): Serial number , Occupy 32 position , Used to identify from TCP Byte stream sent from source to destination , Flag this when the initiator sends data .
Ack(acknowledgement number): Confirmation no. , Occupy 32 position , Only ACK Sign bit is 1 when , Verify that the ordinal field is valid ,Ack=Seq+1.
SYN、Seq、Ack All in TCP Of the message segment TCP In the head .
FIN Is the marker bit , Express “ Request to release connection ” and “ Ready to release the connection ”.

2,PPP Point to point protocol
Point to point agreement (Point to Point Protocol,PPP) It is a link layer protocol designed for simple links such as transmitting data packets between equivalent units .PPP With dynamic allocation IP Address 、 Error detection 、 Authentication etc. function , It can be used on many types of physical media , Including serial cable 、 Telephone line 、 Mobile phones and fiber optics ( for example SDH),PPP Also used in Internet Access .
PPP use 7EH As the beginning and end of a frame (F); Where address field (A) And control domain (C) Take a fixed value (A=FFH,C=03H) ; Protocol domain ( Two bytes ) take 0021H Express IP grouping , take 8021H Represents network control data , take C021H Indicates link control data ; Frame check field (FCS) Also two bytes , It is used to verify the information field . If 7EH, Convert to (7DH,5EH) Two characters . When the information field appears 7DH when , Convert to (7DH,5DH). When... Appears in the information flow ASCII Code control characters ( That is less than 20H), That is, add a 7DH character .

3, The checksum
Calculation method : In the process of data transmission , Treat the sent data segments as a 16 An integer . Add up these integers . And the preceding carry cannot be discarded , Fill in the back , Last reversal , Get checksums .

4, Confirm the response and serial number
Ensure that the data is in order without repetition
Serial number :TCP Each byte of data is numbered during transmission , This is the serial number .
Confirm response :TCP In transit , Every time the receiver receives data , Will confirm and respond to the transmitting party . That is, sending ACK message . This ACK The message contains the corresponding confirmation serial number , Tell sender , What data has been received , Where to send the next data .
5, Over time retransmission
The simple understanding is that the sender waits for a time after sending the data , When the time arrives, I don't receive ACK message , Then resend the data just sent . because TCP Ensure high-performance communication in any environment during transmission , So this maximum timeout ( That is, the waiting time ) It's dynamic computing .
6, The sliding window : Cumulative response and flow control
TCP There's a field in the header called Window, That's the window size .
(1) Cumulative response
With the window , You can specify the window size , The window size means that there is no need to wait for confirmation , And can continue to send the maximum data .
The implementation of windows is actually a cache space opened by the operating system , The sender's host waits until the acknowledgement is returned , The sent data must be kept in the buffer . If you receive a confirmation on time , At this point, the data can be cleared from the cache .
(2) flow control
With the cumulative response , The sender cannot send data to the receiver without thinking , Consider the receiver's processing power . If you have no brain to send data to each other , But the other side can't handle it , Then it will trigger the resend mechanism , This leads to the unprovoked waste of network traffic .
TCP There's a field in the header called Window, That's the window size .
This field tells the sender how many buffers it has to receive data . So the sender can send data according to the processing power of the receiver , The receiver will not be unable to handle it .
therefore , Usually the size of the window is determined by the receiver . The data size sent by the sender cannot exceed the window size of the receiver , Otherwise, the receiver cannot receive the data normally .
Data cached by the sender , According to the treatment, it is divided into four parts , The dark blue box is the send window , The purple box is the available window :

#1 Is sent and received ACK Confirmed data :1~31 byte
#2 Is sent but not received ACK Confirmed data :32~45 byte
#3 Is not sent but the total size is within the processing range of the receiver ( The receiver still has room ):46~51 byte
#4 Is not sent but the total size exceeds the processing range of the receiver ( The receiver has no space ):52 After bytes
7, Congestion control
TCP In transit , When the sender starts sending data , If you send a lot of data at the beginning , Then it may cause some problems . The network may be congested at the beginning , If you throw a lot of data into the network , Then the congestion will intensify . The aggravation of congestion will produce a lot of packet loss , For a large number of timeout retransmissions , Seriously affect transmission .
therefore TCP Introduced Slow start mechanism , When you start sending data , Send a small amount of data first to explore the way . How about the current network state , Then decide how fast to transmit . At this time, a concept called congestion window is introduced . At the beginning of sending, the congestion window is defined as 1, Every time I received ACK The reply , Congestion window plus 1. Before sending data , First, compare the congestion window with the window size fed back by the receiver , Take the smaller value as the actual sending window .
3、 ... and ,TCP Programming steps

Server side : Create socket socket, binding (bind) network address , Set listening (listen), Waiting to accept the connection request (accept), Write (send,write) Or read (read,recv) Information , Close the connection (close)
The end of the service : Create socket socket, Request to connect to the server (connect), Write (send,write) Or read (read,recv) Information , Close the connection (close)
Server code implementation :
#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
int tcp_server_init(const char *ip_addr, const char *port)
{
int r;
/*step1: socket Create a streaming socket */
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
{
perror("socket failed");
return -1;
}
/*step2: bind Bind a network address */
struct sockaddr_in sAddr;// Define the network address of a server
memset(&sAddr, 0 ,sizeof(sAddr));
sAddr.sin_family = AF_INET;//IPV4 agreement
sAddr.sin_addr.s_addr = inet_addr(ip_addr);//right!!
sAddr.sin_port = htons(atoi(port));//right!!
r = bind(sockfd, (struct sockaddr*)&sAddr,sizeof(sAddr));
if(r == -1)
{
perror("bind failed");
return -1;
}
/*step3: listen Set the number of listeners */
r = listen(sockfd, 24);
if(r == -1)
{
perror("listen failed");
return -1;
}
return sockfd;
}
char *a_to_A(char *str)
{
for(int i=0;i<strlen(str);i++)
{
if(str[i]>='a' && str[i]<='z')
{
str[i]-=32;
}
}
return str;
}
void connect_handler(int sock_fd)
{
while(1)
{
char buf[64]={0};
int r = read(sock_fd, buf, 64);
if(r == 0)
break;
write(sock_fd,a_to_A(buf),strlen(buf)+1);
}
close(sock_fd);
}
int main(int argc, char **argv)
{
int sockfd = tcp_server_init(argv[1], argv[2]);
/*step4: accept Waiting to be connected */
while(1)
{
struct sockaddr_in cAddr;// Used to save the network address of the client
socklen_t addrlen = sizeof(cAddr);
int accept_fd = accept(sockfd, (struct sockaddr *)&cAddr, &addrlen);
if(accept_fd > 0)
{
printf("connect form %s[%d]\n",inet_ntoa(cAddr.sin_addr), ntohs(cAddr.sin_port));
pid_t pid = fork();// Concurrent servers
if(pid > 0)
{
close(accept_fd);
}
else // Generate a sub process to provide services
{
connect_handler(accept_fd);
exit(0);
}
}
}
}
Client code implementation :
#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
int tcp_client_init()
{
int r;
/*step1: socket Create a streaming socket */
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
{
perror("socket failed");
return -1;
}
return sockfd;
}
void *read_socket(void *arg)
{
int sockfd = *(int*)arg;
while(1)
{
char buf[128];
read(sockfd, buf, 128);
puts(buf);
}
}
int main(int argc, char **argv)
{
int sockfd = tcp_client_init();
pthread_t tid;
if(pthread_create(&tid, NULL, read_socket, &sockfd))
{
perror("pthread_create failed");
return -1;
}
struct sockaddr_in sAddr;// Define the network address of a server
memset(&sAddr, 0 ,sizeof(sAddr));
sAddr.sin_family = AF_INET;//IPV4 agreement
sAddr.sin_addr.s_addr = inet_addr(argv[1]);//right!!
sAddr.sin_port = htons(atoi(argv[2]));//right!!
int r = connect(sockfd, (struct sockaddr *)&sAddr,sizeof(sAddr));
if(r == -1)
{
perror("connect failed");
return -1;
}
while(1)
{
char str[64];
gets(str);
if(strcmp(str,"quit") == 0)
{
break;
}
write(sockfd,str,strlen(str)+1);
}
close(sockfd);
}
边栏推荐
- 手机号,固话正则表达式
- Data can't lie. Plato farm is the leader of the meta universe
- Translation recommendation | debugging bookkeeper protocol - unbounded ledger
- fastjson中@jsonType注解的功能简介说明
- TCP 基础知识
- 【Gradle】This version of the JMH Gradle plugin requires Gradle 6+, you are using 6.6.
- How to learn so many conceptual things in database? Seeking method
- 图解 3 种主流企业架构模式(建议收藏!)
- 多线程一定能优化程序性能吗?
- 深度学习必懂的 13 种概率分布
猜你喜欢

The secret behind three salary increases a year

数据不会说谎,Plato Farm就是元宇宙龙头

一文读懂Plato Farm的ePLATO,以及其高溢价缘由
![[ESP32][esp-idf] esp32s3快速搭建LVGLV7.9](/img/39/8efef047d0a9223b97819a54b5edf8.png)
[ESP32][esp-idf] esp32s3快速搭建LVGLV7.9

Time series analysis 41 - time series prediction tbats model

In hot weather, the line of defense for safe production was strengthened, and Guangzhou Haizhu District carried out emergency drills for gas stations

Software testing and quality learning notes 2 - black box testing

Business visualization - make your flowchart'run'(4. Actual business scenario test)

TCP 基础知识

软件测试与质量学习笔记2----黑盒测试
随机推荐
能够遍历一个文件夹下的所有文件和子文件夹
这款微信插件太好用了
OSPF的拓展配置,选路原则,防环及重发布
软件测试与质量学习笔记2----黑盒测试
Feign call exception [running, pool size = 10, active threads = 10, queued tasks = 0, completed tasks = n]
SQL server, MySQL master-slave construction, EF core read-write separation code implementation
fastjson中@jsonType注解的功能简介说明
C countdown tool
Introduction to timebasedrollingpolicy
redis的基础知识
Symbolic operation of MATLAB
pycharm使用conda调用远程服务器
How to get more marks in the game under the new economic model of Plato farm
ES6新特性
The victory of Dao community, tiger Dao VC wins in governance and consensus
[ESP32][esp-idf] esp32s3快速搭建LVGLV7.9
数据库高级学习笔记--系统包
In php7?? And?: Differences between
3分钟告诉你如何成为一名黑客|零基础到黑客入门指南,你只需要掌握这五点能力
刚获融资的Espresso Systems,知识产权与团队道德双双陷入困境