// 发送数据
ssize_t sendn(int fd, void *buf, size_t count, int flags)
{
size_t nleft = count;
ssize_t nread;
char *pbuf = (char*)buf;
while(nleft > 0)
{
if ((nread = send(fd, pbuf, nleft, flags)) < 0)
{
if (errno == EINTR)//信号中断
{
continue;
}
return -1;
}else if (nread == 0)//连接中断
{
return count - nleft;//返回发送的字节数
}
nleft -= nread;//计算剩余字节数
pbuf += nread;//移动指针
}
return count;
}
// 接收函数
ssize_t recvn(int fd, void* buf, size_t count, int flags)
{
size_t nleft = count;
ssize_t nwrite ;
char *pbuf = (char*)buf;
while(nleft > 0)
{
if ((nwrite = recv(fd, pbuf, nleft, flags)) < 0)
{
if (errno == EINTR)
{
continue;
}
return -1;
}else if (nwrite == 0)
{
return count - nleft;
}
nleft -= nwrite;
pbuf +=nwrite;
}
return count;
}
通过上面的改造发送数据必须使用定长包或者有 协议的包