下面提供一种recvfrom的非阻塞设置方法,希望能对不清楚的同仁能有所帮助。
if (-1 == fcntl(iSocketfd, F_SETFL, O_NONBLOCK))
{
printf("fcntl socket error!\n");
return -1;
}
int iSocketLen = sizeof(struct sockaddr_in);
/* set recvfrom from server timeout */
struct timeval tv;
fd_set readfds;
tv.tv_sec = TIME_OUT_TIME;
tv.tv_usec = 0;
FD_ZERO(&readfds);
FD_SET(iSocketfd, &readfds);
if (select(iSocketfd+1,&readfds,NULL, NULL, &tv) > 0)
{
iRecvNum = recvfrom(iSocketfd,(void *)stRecvBuf,sizeof(*(stRecvBuf)),0, (struct sockaddr *)stRemote,&iSocketLen);
if (-1 == iRecvNum)
{
printf("received data error!\n");
iRet=0;
}
iRet=1;
printf("iRecvNum is %d\n",iRecvNum);
}
else
{
printf("timeout!there is no data arrived!\n");
iRet=0;
}
上面的代码只是我程序中的一段,所以上下文衔接肯定不好,但基本意思已经表达得很清楚了。另外,因为代码量太小,所以就不上传源码了:)
欢迎转载,请注明出处。
阅读(16371) | 评论(0) | 转发(2) |