1 recv 如何设置超时
1 首先说明一样,跟第四个参数关系不大
2 函数填写位置
3 打印 error 需要的库
struct timeval timeout={3,0};//3s
ssize_t ret1;
int ret=setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,(const char*)&timeout,sizeof(timeout)); //在recv 之前设置就行
if (ret != 0)
printf("setsockopt fail\n");
ret1=recv(sockfd,buf,N,0);
if(ret1==-1&&errno==EAGAIN){ //这个 errno 对应的头文件 #include<errno.h>
printf("timeout\n");
}
2 因为 recv 指定的 size 并不一定能接收到,所以要多次接收
#define N 50
ssize_t recv_complete(int sockfd, void *buf, size_t len)
{
ssize_t size = 0;
ssize_t size_totol = len;
while(size_totol >= N) {
size = recv(sockfd, buf, N, 0);
if(size==-1&&errno==EAGAIN){
printf("timeout\n");
}
size_totol = size_totol - size;
buf = buf + size;
}
while (size_totol > 0) {
size = recv(sockfd, buf, size_totol, 0);
if(size==-1&&errno==EAGAIN){
printf("timeout\n");
}
size_totol = size_totol - size;
buf = buf + size;
}
if(size_totol < 0)
printf("recv errno\n");
}
3 制定好通信协议当收到某个字符串就结束接收
ssize_t recv_until(int sockfd, void *buf, char*until_word)
{
ssize_t size = 0;
while (strstr(buf, until_word) == NULL) {
size = recv(sockfd, buf, N, 0);
if(size == -1&&errno == EAGAIN){
printf("timeout\n");
}
if (strstr(buf, until_word) != NULL)
return 0;
buf = buf + size;
}
}

2479

被折叠的 条评论
为什么被折叠?



