/* 检测fd句柄是否可读,ms毫秒超时
参数:
df [in] 检测的句柄
ms [in] 超时,毫秒
返回:
1 可读,或者已经断开
0 超时,仍然不可读
-1 错误
*/
int IsReadable(SOCKET fd, int ms)
{
//描述符集
fd_set fdSet, oldFdSet;
FD_ZERO(&fdSet);
FD_SET(fd, &fdSet);
// select超时时间
timeval tm;
tm.tv_sec = 0;
tm.tv_usec = ms*1000;
FD_ZERO(&oldFdSet);
oldFdSet = fdSet;
int ret = select(fd+1, &oldFdSet, NULL, NULL, &tm);
if (SOCKET_ERROR == ret)
return -1;
else if (ret == 0)
return 0; // 不可读
else if (FD_ISSET(fd, &oldFdSet))
return 1; // 可读
else
return 0; // 不可读
}
int Readn(SOCKET sockfd, char *buf, int count, int msec)
{
//fd_set rfds,afds;
//struct timeval xt;
int ret = 0;
int rc = 0, n = 0;
while (1)
{
ret = IsReadable(sockfd, msec);
if (ret == -1)
{
if (errno == EINTR)
continue;
return -1;
}
else if (ret == 0)
{
return -2;
}
//rc = read(sockfd, buf + n, count - n);
rc = recv(sockfd, buf + n, count - n,0);
if (rc<0)
{
if (errno == EINTR)
continue;
else
return -1;
}
if (rc == 0)
{
return(0);
}
n += rc;
if (n == count)
{
return (count);
}
}
}
套接字(描述符)读取指定的字节数
Guess you like
Origin blog.csdn.net/thequitesunshine007/article/details/119900546
Recommended
Ranking