recv 实际问题

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;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值