Posted on 2010-09-14 16:38
杨书童 阅读(3885)
评论(0) 编辑 收藏 引用 所属分类:
基础知识-经验之谈
linux:
1![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
struct timeval timeout=
{3,0};//3s
2![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
3
int ret=setsockopt(sock_fd,SOL_SOCKET,SO_SNDTIMEO,&timeout,sizeof(timeout));
4![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
5
int ret=setsockopt(sock_fd,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout));
6![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
7
如果ret==0 则为成功,-1为失败,这时可以查看errno来判断失败原因
8![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
9
int recvd=recv(sock_fd,buf,1024,0);
10![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
11
if(recvd==-1&&errno==EAGAIN)
12![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
13![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
14![](http://www.cppblog.com/Images/OutliningIndicators/InBlock.gif)
15
printf("timeout\n");
16![](http://www.cppblog.com/Images/OutliningIndicators/InBlock.gif)
17
}
18![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
19![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
windows:
int timeout = 3000; //3s
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
int ret=setsockopt(sock_fd,SOL_SOCKET,SO_SNDTIMEO,&timeout,sizeof(timeout));
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)
int ret=setsockopt(sock_fd,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout));
![](http://www.cppblog.com/Images/OutliningIndicators/None.gif)