当前位置:网站首页>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 .
边栏推荐
- Gorilla/mux framework (RK boot): add tracing Middleware
- The difference between single power amplifier and dual power amplifier
- Xiangong intelligent obtained hundreds of millions of yuan of b-round financing to accelerate the process of building non-standard solutions with standardized products
- Alibaba cloud container service differentiation SLO hybrid technology practice
- Blue Bridge Cup -- guess age
- Common mode interference of EMC
- C # basic knowledge (2)
- Learning notes of raspberry pie 4B - IO communication (SPI)
- 33 restrict the input of qlineedit control (verifier)
- [note] IPC traditional interprocess communication and binder interprocess communication principle
猜你喜欢

Sort merge sort

Actual combat | use composite material 3 in application

Schematic diagram of crystal oscillator clock and PCB Design Guide

Take you to master the formatter of visual studio code

Pyqt5 sensitive word detection tool production, operator's Gospel

In VS_ In 2019, scanf and other functions are used to prompt the error of unsafe functions

Pan Yueming helps Germany's Rochester Zodiac custom wristwatch

Loop compensation - explanation and calculation of first-order, second-order and op amp compensation

How to make icons easily

"Learning notes" recursive & recursive
随机推荐
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
2022.02.14
Errors taken 1 Position1 argument but 2 were given in Mockingbird
Format cluster and start cluster
[Happy Valentine's day] "I still like you very much, like sin ² a+cos ² A consistent "(white code in the attached table)
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
How to quickly build high availability of service discovery
Analysis of refrigeration and air conditioning equipment operation in 2022 and examination question bank of refrigeration and air conditioning equipment operation
C # basic knowledge (2)
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
C # basic knowledge (1)
D24:divisor and multiple (divisor and multiple, translation + solution)
Loop compensation - explanation and calculation of first-order, second-order and op amp compensation
Alibaba cloud container service differentiation SLO hybrid technology practice
[issue 16] golang's one-year experience in developing Purdue Technology
How to prevent malicious crawling of information by one-to-one live broadcast source server
Druids connect to mysql8.0.11
[15th issue] Tencent PCG background development internship I, II and III (OC)
Fashion cloud interview questions series - JS high-frequency handwritten code questions
Deep learning ----- using NN, CNN, RNN neural network to realize MNIST data set processing