TCP/IP Winsock编程要点(3)
4、同步方式中解决recv,send阻塞问题
采用select函数解决,在收发前先检查读写可用状态。
A、读
例子:
TIMEVAL tv01 = {0, 1};//1ms钟延迟,实际为0-10毫秒
int nSelectRet;
int nErrorCode;
FD_SET fdr = {1, sConnect};
nSelectRet=::select(0, &fdr, NULL, NULL, &tv01);//检查可读状态
if(SOCKET_ERROR==nSelectRet)
{
nErrorCode=WSAGetLastError();
TRACE("select read status errorcode=%d",nErrorCode);
::closesocket(sConnect);
goto 重新连接(客户方),或服务线程退出(服务方);
}
if(nSelectRet==0)//超时发生,无可读数据
{
继续查读状态或向对方主动发送
}
else
{
读数据
}
B、写
TIMEVAL tv01 = {0, 1};//1ms钟延迟,实际为9-10毫秒
int nSelectRet;
int nErrorCode;
FD_SET fdw = {1, sConnect};
nSelectRet=::select(0, NULL, NULL,&fdw, &tv01);//检查可写状态
if(SOCKET_ERROR==nSelectRet)
{

