当前位置:网站首页>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 .
边栏推荐
- Ppt image processing
- Maxwell equation and Euler formula - link
- [MySQL] sql99 syntax to realize multi table query
- D27:mode of sequence (maximum, translation)
- Bufferpool caching mechanism for executing SQL in MySQL
- 2022 free examination questions for hoisting machinery command and hoisting machinery command theory examination
- Amway by head has this project management tool to improve productivity in a straight line
- How to write a good title of 10w+?
- Gorilla/mux framework (RK boot): add tracing Middleware
- Flutter internationalized Intl
猜你喜欢

SDMU OJ#P19. Stock trading

IO flow review

Gorilla/mux framework (RK boot): add tracing Middleware

How the computer flushes the local DNS cache

2022.02.13

Ppt image processing

Fluent learning (5) GridView

Opengauss database log management guide

Pyqt5 sensitive word detection tool production, operator's Gospel

Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
随机推荐
Gorilla/mux framework (RK boot): add tracing Middleware
URLEncoder. Encode and urldecoder Decode processing URL
Open 2022 efficient office, starting from project management
How to solve the problem of computer networking but showing no Internet connection
Unsafe and CAS principle
What are the securities companies with the lowest Commission for stock account opening? Would you recommend it? Is it safe to open an account on your mobile phone
Opengauss database log management guide
The interviewer's biggest lie to deceive you, bypassing three years of less struggle
Recursion and recursion
Alibaba cloud container service differentiation SLO hybrid technology practice
leetcode-43. String multiplication
Weekly leetcode - nc9/nc56/nc89/nc126/nc69/nc120
NPM script
2022 t elevator repair registration examination and the latest analysis of T elevator repair
Cgb2201 preparatory class evening self-study and lecture content
2.14 summary
Sort merge sort
A treasure open source software, cross platform terminal artifact tabby
How the computer flushes the local DNS cache
Pandaoxi's video