使用recvfrom来接受数据时,如果没有数据回来,会一直阻塞下去。
如果不想一直阻塞,可以通过设置socket option的方式来对
recvfrom 设置超时机制。
SO_RCVTIMEO
Sets the timeout value that specifies the maximum amount of time an input function waits until it completes. It accepts a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to complete. If a receive operation has blocked for this much time without receiving additional data, it shall return with apartial count or errno set to [EAGAIN] or [EWOULDBLOCK] if no data is received. The default for this option is zero, which indicates that a receive operation shall not time out. This option takes a timeval structure. Note that not all implementa- tions allow this option to be set
- struct timeval tv;
- int ret;
- tv.tv_sec = 10;
- tv.tv_usec = 0;
- if(setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv))<0){
- printf("socket option
SO_RCVTIMEO not support\n");
- return;
- }
- if ((
ret = recvfrom(s, buf, sizeof buf, 0, NULL,NULL)) < 0)
- {
- if(ret == EWOULDBLOCK || ret== EAGAIN )
- printf("recvfrom timeout\n");
- else
- printf("recvfrom err:%d\n",ret);
- }
阅读(20183) | 评论(0) | 转发(1) |