当前位置:网站首页>How to make recv have a little temper?
How to make recv have a little temper?
2022-07-03 23:24:00 【Tao song remains the same】
Hello everyone , I'm brother Tao .
today , Let's talk about TCP In network programming recv function . We know ,recv It's a blocking function , When no data is received , Will wait for the data foolishly .
that , How to let recv The function is a little grumpy , Instead of waiting foolishly ?select Functions can top . Next , Let's fight , Deepen the understanding of network programming .
Hand painted by Taoge
One . Grumpy recv function
When recv When a function has no temper , Just wait foolishly , Till the end of time . Let's look at the server program , And let the server run first .
We see , When building a TCP After connection , The server deliberately waited 3 Seconds to send data , So can the client afford to wait ? Are you patient ?
#include <stdio.h>
#include <winsock2.h> // winsock Interface
#pragma comment(lib, "ws2_32.lib") // winsock Realization
int main()
{
WORD wVersionRequested; // Double byte ,winsock Version of the library
WSADATA wsaData; // winsock Information about library version
wVersionRequested = MAKEWORD(1, 1); // 0x0101 namely :257
// load winsock Library and determine winsock edition , The system will fill in the data wsaData in
WSAStartup( wVersionRequested, &wsaData );
// AF_INET Said the TCP/IP Protocol family
// SOCK_STREAM Said the TCP agreement
// 0 Is the usual default
unsigned int sockSrv = socket(AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN addrSrv;
addrSrv.sin_family = AF_INET; // TCP/IP Protocol family
addrSrv.sin_addr.S_un.S_addr = inet_addr("0.0.0.0");
addrSrv.sin_port = htons(8888); // socket Corresponding port
// take socket Bind to something IP And port (IP Identify the host , The port identifies the communication process )
bind(sockSrv,(SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
listen(sockSrv, 5);
SOCKADDR_IN addrClient;
int len = sizeof(SOCKADDR);
while(1)
{
unsigned int sockConn = accept(sockSrv,(SOCKADDR*)&addrClient, &len);
printf("accept is returned\n");
Sleep(3000);
char sendBuf[100] = "hello";
send(sockConn, sendBuf, strlen(sendBuf) + 1, 0); // Send data to client , This is the last parameter 0
//closesocket(sockConn);
}
closesocket(sockSrv);
WSACleanup();
return 0;
}
next , Let's look at the client program , And let the client run . Run client program , You can find , Although the server deliberately delayed 3 second , But customers have unlimited patience , Still get data .
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(1, 1);
WSAStartup( wVersionRequested, &wsaData );
SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(8888);
int ret = connect(sockClient, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
printf("connect ret is %d\n", ret);
char recvBuf[200] = "x";
ret = recv(sockClient, recvBuf, 100, 0);
if(0 > ret)
{
printf("recv error");
return -3;
}
if(0 == ret)
{
printf("recv ret is %d\n", ret);
return -4;
}
printf("%s\n", recvBuf);
while(1);
closesocket(sockClient);
WSACleanup();
return 0;
}
Two . Temperamental recv function
recv Function should be a little grumpy , wait for 4 Seconds later , You don't come , I won't wait . How to achieve ? You can use select Timeout feature of function , The client program is as follows :
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(1, 1);
WSAStartup( wVersionRequested, &wsaData );
SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(8888);
int ret = connect(sockClient, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
printf("connect ret is %d\n", ret);
fd_set rfds;
struct timeval timeout = {4, 0};
FD_ZERO(&rfds);
FD_SET(sockClient, &rfds);
ret = select(-1, &rfds, NULL, NULL, &timeout);
printf("select ret is %d\n",ret);
if(0 > ret)
{
printf("select error\n");
return -1;
}
if(0 == ret)
{
printf("time out\n");
return -2;
}
if(FD_ISSET(sockClient, &rfds))
{
char recvBuf[200] = "x";
ret = recv(sockClient, recvBuf, 100, 0);
if(0 > ret)
{
printf("recv error");
return -3;
}
if(0 == ret)
{
printf("recv ret is %d, buf is %s\n", ret, recvBuf);
return -4;
}
printf("%s\n", recvBuf);
}
while(1);
closesocket(sockClient);
WSACleanup();
return 0;
}
The patience of the client is only 4 second , Client said : The server , you TM Of , Before I establish with you TCP After relationship , If you 4 No data in seconds , I'll ignore you .
Run the program , You can see , The client can receive data , Because the server is 4 The data was transmitted in seconds , The client's patience is not reached 4 Second limit .
If you change the endurance value of the client to 2 second , What will happen then ? After testing , Client, etc 2 Seconds later , I don't want to wait , Naturally, no data was received , Have enough temper .
In the actual work of network programming , Almost all network related operations need to set timeout , For example, connection timeout 、 Send timeout 、 Receive timeout , Everywhere .
When learning computer network and network programming , Many people have prepared a lot of eight part essays for the written interview , Like three handshakes and four waves , These preparations are necessary .
However , These are not enough . Computer network is a subject with strong practicality , I personally suggest writing more programs 、 Multi debugging 、 Grab more bags , Then compare it with the theory .
边栏推荐
- A preliminary study on the middleware of script Downloader
- Pan Yueming helps Germany's Rochester Zodiac custom wristwatch
- How the computer flushes the local DNS cache
- Flutter internationalized Intl
- [note] IPC traditional interprocess communication and binder interprocess communication principle
- The difference between single power amplifier and dual power amplifier
- Cgb2201 preparatory class evening self-study and lecture content
- Deep learning ----- using NN, CNN, RNN neural network to realize MNIST data set processing
- "Learning notes" recursive & recursive
- Go error collection | talk about the difference between the value type and pointer type of the method receiver
猜你喜欢
How to restore the factory settings of HP computer
To rotate 90 degrees clockwise and modify the video format
2022 t elevator repair registration examination and the latest analysis of T elevator repair
Pointer concept & character pointer & pointer array yyds dry inventory
2022.02.14
2022 examination of safety production management personnel of hazardous chemical production units and examination skills of safety production management personnel of hazardous chemical production unit
The interviewer's biggest lie to deceive you, bypassing three years of less struggle
[Happy Valentine's day] "I still like you very much, like sin ² a+cos ² A consistent "(white code in the attached table)
Ppt image processing
540. Single element in ordered array
随机推荐
Les sociétés de valeurs mobilières dont la Commission d'ouverture d'un compte d'actions est la plus faible ont ce que tout le monde recommande.
Fluent learning (4) listview
Recursion and recursion
FPGA tutorial and Allegro tutorial - link
Enter MySQL in docker container by command under Linux
JarPath
The 2022 global software R & D technology conference was released, and world-class masters such as Turing prize winners attended
Hcip day 12 notes
Current detection circuit - including op amp current scheme
In 2022, 6G development has indeed warmed up
Overview of Yunxi database executor
[untitled]
ADB command to get XML
Interesting 10 CMD commands
Pyqt5 sensitive word detection tool production, operator's Gospel
Es6~es12 knowledge sorting and summary
540. Single element in ordered array
pycuda._ driver. LogicError: explicit_ context_ dependent failed: invalid device context - no currently
A preliminary study on the middleware of script Downloader
Comment obtenir une commission préférentielle pour l'ouverture d'un compte en bourse? Est - ce que l'ouverture d'un compte en ligne est sécurisée?