UDP的recvfrom超时:
fd_set ReadSet;
FD_ZERO(&ReadSet);
FD_SET(sockEncoder,&ReadSet);
timeout.tv_sec = 1;
timeout.tv_usec = 0;
ret = select(0, &ReadSet, NULL, NULL, &timeout);
if(ret>0)
{
ret = recv(sockEncoder, buf, sizeof(buf), 0);
if(0 > ret)
{
cout<<"SendToEncoder() "<<"System Error: recv from encoder"<<", error-"<<GetLastError()<<endl;
closesocket(sockEncoder);
return FALSE;
}
if(0 == ret)
{
cout<<"SendToEncoder() "<<"recv from encoder"<<" timeout"<<endl;
return FALSE;
}
TCP connect 超时:
//使不阻塞在connect
unsigned long ul = 1;
ioctlsocket(sockEncoder, FIONBIO, &ul); //设置为非阻塞模式
bool suc = false;
timeval tm;
fd_set set;
char error;
int len = sizeof(char);
if(connect(sockEncoder, (sockaddr*)&encoderAddr, sizeof(sockaddr)) == -1)
{
tm.tv_sec = 3;
tm.tv_usec = 0;
FD_ZERO(&set);
FD_SET(sockEncoder, &set);
if( select(sockEncoder+1, NULL, &set, NULL, &tm) > 0)//是否可写
{
getsockopt(sockEncoder,SOL_SOCKET,SO_ERROR,&error,&len);
if(error == 0)
suc = true;//correct IP
else
suc = false;
}
else
suc = false;//wrong IP after time_out
}
else
suc = true;
ul = 0;
ioctlsocket(sockEncoder, FIONBIO, &ul); //设置为阻塞模式
if(!suc)
{
closesocket( sockEncoder );
return FALSE;
}
//下面进行发包收包操作