每次发送后, 用select函数判断超时情况, 下面这个可是在我的项目中久经考验的一个函数了:
int RecvTimeOut(int fd, unsigned int sec)
{
fd_set fs;
struct timeval timeout;
int n;
FD_ZERO(&fs);
FD_SET((unsigned int)fd,&fs);
timeout.tv_sec = sec;
timeout.tv_usec = 0;
n=select(fd+1,&fs,NULL,NULL,&timeout);
return n;
}
例:
void __fastcall TForm1::Button2Click(TObject *Sender)
{
ClientSocket1->Socket->SendBuf(100, sizeof(int));
//如果60秒还没有回应, 就判断超时(或认为网络中断也行), 关闭连接
if (RecvTimeOut(ClientSocket1->Socket->Handle, 60))
ClientSocket1->Close();
}