当前位置:网站首页>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 .
边栏推荐
- C summary of knowledge point definitions, summary notes
- Minimum commission for stock account opening. Stock account opening is free. Is online account opening safe
- SQL data update
- Blue Bridge Cup -- Mason prime
- Esp-idf turns off serial port log output.
- Idea integrates Microsoft TFs plug-in
- [Android reverse] use the DB browser to view and modify the SQLite database (copy the database file from the Android application data directory | use the DB browser tool to view the data block file)
- How to prevent malicious crawling of information by one-to-one live broadcast source server
- Pyqt5 sensitive word detection tool production, operator's Gospel
- Apple released a supplementary update to MacOS Catalina 10.15.5, which mainly fixes security vulnerabilities
猜你喜欢

2022 t elevator repair registration examination and the latest analysis of T elevator repair

Schematic diagram of crystal oscillator clock and PCB Design Guide

Fluent learning (4) listview

User login function: simple but difficult

X Opencv feature point detection and matching

Recursive least square adjustment

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

How can enterprises and developers take advantage of the explosion of cloud native landing?

Alibaba cloud container service differentiation SLO hybrid technology practice

Esp-idf turns off serial port log output.
随机推荐
Amway by head has this project management tool to improve productivity in a straight line
SQL data update
D23:multiple of 3 or 5 (multiple of 3 or 5, translation + solution)
Pan Yueming helps Germany's Rochester Zodiac custom wristwatch
How to quickly build high availability of service discovery
[untitled]
Scratch uses runner Py run or debug crawler
X Opencv feature point detection and matching
Hcip day 12 notes
How to restore the factory settings of HP computer
A treasure open source software, cross platform terminal artifact tabby
D28:maximum sum (maximum sum, translation)
Idea integrates Microsoft TFs plug-in
Blue Bridge Cup -- Mason prime
NPM script
SDMU OJ#P19. Stock trading
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
Open 2022 efficient office, starting from project management
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
Qtoolbutton - menu and popup mode