socket超时设置
//--------------------------------------------------------------------------
//设置为非阻塞方式连接
unsigned long ul = 1;
int ret = ioctlsocket(m_sSocket, FIONBIO, (unsigned long*)&ul);
if(ret == SOCKET_ERROR)
{
err = WSAGetLastError();
closesocket(m_sSocket);
m_sSocket = NULL;
return FALSE;
}
struct timeval timeout ; // 超时结构
fd_set r;
FD_ZERO(&r);
FD_SET(m_sSocket, &r);
timeout.tv_sec = iTimeout; // 连接超时设置
timeout.tv_usec =0;
connect(m_sSocket,(LPSOCKADDR)&server,sizeof(SOCKADDR));
ret = select(0, 0, &r, 0, &timeout);
if ( ret <= 0 )
{
err = WSAGetLastError();
closesocket(m_sSocket);
m_sSocket = NULL;
return FALSE;
}
//设回阻塞模式
ul = 0 ;
ret = ioctlsocket(m_sSocket, FIONBIO, (unsigned long*)&ul);
//--------------------------------------------------------------------------
//接收超时
//-------------------------------------------
//接收超时设置
struct timeval outtime ; // 超时结构
FD_SET fdr = {1, m_sSocket};
outtime.tv_sec = timeout;
outtime.tv_usec =0;
int nSelectRet;
//------------------------------------------------------------
//网络只认单字节串,而EVC里多字节;发送的UNICODE串转换成单字节串
UINT nLen = len * 2;
char *pByte = new char[nLen+1];
memset(pByte, 0, nLen+1);
WideCharToMultiByte(CP_ACP, NULL, buf, wcslen(buf),pByte, nLen, NULL, NULL);
int nRet;
nSelectRet=::select(0, &fdr, NULL, NULL, &outtime); //检查可读状态
if(SOCKET_ERROR==nSelectRet)
{
err = WSAGetLastError();
closesocket(m_sSocket);
m_sSocket = NULL;
return -1;
}
if(nSelectRet==0) //超时发生,无可读数据
{
AfxMessageBox(L"接收超时");
err = WSAGetLastError();
closesocket(m_sSocket);
m_sSocket = NULL;
return -1;
}
else
{
//接收数据
nRet = recv(m_sSocket, pByte, nLen, 0);
if(nRet == SOCKET_ERROR)
{
err = WSAGetLastError();
}
}
//-------------------------------------------
MultiByteToWideChar(CP_ACP, NULL, pByte, nLen, buf, len);
delete [] pByte;
pByte = NULL;
//---------------------------------------------------------------------