1. 函数描述
#include <sys/socket.h>
ssize_t recv(int sockfd, void *buf, size_t len, int flags);
函数功能:接收对方发送当数据
函数参数:
sockfd: 通信文件描述符
buf: 应用缓存,用于存放要发送到数据可以是任何类型:结构体,int , char,float,字符串
len: buf的大小
flags: 一般设置为0,此时send为阻塞式发送即发送不成功会一直阻塞,直到被某个信号终端终止,或者直到发送成功为止。
指定MSG_NOSIGNAL,表示当连接被关闭时不会产生SIGPIPE信号
指定MSG_DONTWAIT 表示非阻塞发送
指定MSG_OOB 表示带外数据
函数返回值
- >0:接收到的数据大小
- ==0:连接关闭
- <0:出错
在出错的情况下,这三种错误下认为连接是正常的,继续接收
if(errno == EINTR ||(errno == EAGAIN)||errno == EWOULDBLOCK)
continue;
if(FD_ISSET(connfd,&r_set)
{
int irecv,iunrecv;
iunrecv = length;
while(iunrecv>0)
{
irecv = recv(concfd,buff,iunrecv,0)
if(irecv==0)
{
printf("recv error:%s",strerror(errno));
return -1;
}
if(irecv<0)
{//这条判断是针对非阻塞的情况下,会发生的错误//当阻塞的情况下,recv函数会直接阻塞在调用的地方,不会执行到这里。
if(errno == EINTR ||(errno == EAGAIN)||errno == EWOULDBLOCK)
continue;
//阻塞和非阻塞都会产生
printf("recv error:%s",strerror(errno));
return -1;
}
iunrecv -= irecv;
buff += irecv;
}
}
注意
recv的返回值为0时,表示连接关闭,并不是说没有读到数据,因为,对于阻塞的套接字,没有读到数据,函数不会返回,会阻塞等待。对于非阻塞的套接字,没有读到数据,函数会返回-1,错误号时 EAGAIN。