当前位置:网站首页>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 .
边栏推荐
- Interesting 10 CMD commands
- In VS_ In 2019, scanf and other functions are used to prompt the error of unsafe functions
- Comparable interface and comparator interface
- [source code] VB6 chat robot
- 2/14 (regular expression, sed streaming editor)
- finalize finalization finally final
- How to quickly build high availability of service discovery
- How to solve the "safe startup function prevents the operating system from starting" prompt when installing windows10 on parallel desktop?
- Fashion cloud interview questions series - JS high-frequency handwritten code questions
- Day30-t540-2022-02-14-don't answer by yourself
猜你喜欢

Deep learning ----- using NN, CNN, RNN neural network to realize MNIST data set processing

Alibaba cloud container service differentiation SLO hybrid technology practice

Analysis of refrigeration and air conditioning equipment operation in 2022 and examination question bank of refrigeration and air conditioning equipment operation

How to quickly build high availability of service discovery

Take you to master the formatter of visual studio code

How to solve the "safe startup function prevents the operating system from starting" prompt when installing windows10 on parallel desktop?

leetcode-43. String multiplication

SDMU OJ#P19. Stock trading

Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?

IO flow review
随机推荐
Pandaoxi's video
炒股开户佣金优惠怎么才能获得,网上开户安全吗
Take you to master the formatter of visual studio code
Alibaba cloud container service differentiation SLO hybrid technology practice
How to connect a laptop to a projector
Design of logic level conversion in high speed circuit
33 restrict the input of qlineedit control (verifier)
Fluent learning (5) GridView
How to quickly build high availability of service discovery
C3p0 connection MySQL 8.0.11 configuration problem
Comparable interface and comparator interface
How to make icons easily
[untitled]
How to solve the "safe startup function prevents the operating system from starting" prompt when installing windows10 on parallel desktop?
[note] glide process and source code analysis
What are the common computer problems and solutions
Hcip 13th day notes
540. Single element in ordered array
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
Summary of fluent systemchrome