class CYBlockSocket
{
protected:
CStringA m_strIP;
UINT m_nPort;
SOCKET m_hSocket;
public:
SOCKET GetHandle()
{
return m_hSocket;
}
CYBlockSocket():m_hSocket(INVALID_SOCKET)
{
}
~CYBlockSocket()
{
if (m_hSocket!=INVALID_SOCKET) closesocket(m_hSocket);
}
bool Create(const char * szIP, UINT nPort, int nTimeout=5, int nSocketType=SOCK_STREAM)
{
SOCKADDR_IN addrClient;
timeval timeout={ nTimeout,0};
fd_set fdConnect;
unsigned long ul = 1;
if (INVALID_SOCKET!=m_hSocket)
Close();
m_hSocket=socket(AF_INET,nSocketType,0);
if (INVALID_SOCKET==m_hSocket)
return false;
addrClient.sin_addr .S_un .S_addr =inet_addr(szIP);
addrClient.sin_family =AF_INET;
addrClient.sin_port =htons(nPort);
int nLen=sizeof(SOCKADDR);
if (nTimeout!=-1)
{
SetNoBlock();//改成非阻塞状态
connect(m_hSocket,(SOCKADDR *)&addrClient,nLen);
FD_ZERO(&fdConnect);
FD_SET(m_hSocket, &fdConnect);
if (select(0, 0, &fdConnect, 0, &timeout)<=0)
{
closesocket(m_hSocket);
m_hSocket=INVALID_SOCKET;
return false;
}
SetNoBlock(false);//还原成阻塞状态
}
else
if (connect(m_hSocket,(SOCKADDR *)&addrClient,nLen))
return false;
m_strIP=szIP;
m_nPort=nPort;
return true;
}
int Close()
{
int nRet=closesocket(m_hSocket);
m_hSocket=INVALID_SOCKET;
return nRet;
}
int Send(const void *lpBuf, int nLen)
{
if (m_hSocket==INVALID_SOCKET)
return 0;
int nRet=send(m_hSocket,(const char *)lpBuf,nLen,0);
if (GetLastError()==WSAECONNRESET)
{
if (nRet=Create(m_strIP,m_nPort))
return nRet;
nRet=send(m_hSocket,(const char *)lpBuf,nLen,0);
}
if (nRet==-1)
Close();
return nRet;
}
bool Recv(void * pData,UINT * puLen,int usTimeout,UINT nMaxbuf=1024)
{
if (m_hSocket==INVALID_SOCKET)
return 0;
int nRet;
if (usTimeout!=-1)
setsockopt(m_hSocket,SOL_SOCKET,SO_RCVTIMEO,(char *)&usTimeout,sizeof(usTimeout));
nRet=recv(m_hSocket,(char *)pData,nMaxbuf,0);
if (nRet==0)
{
Close();//对方断开,或者这里的socket有错误, ==-1,一般表示超时
return false;
}
if (nRet==-1) return false;
* puLen=nRet;
return true;
}
int SetTimeout(int nRecv, int nSend=-1)
{
if (nRecv!=-1) setsockopt(m_hSocket,SOL_SOCKET,SO_RCVTIMEO,(char *)&nRecv,sizeof(nRecv));
if (nSend!=-1) setsockopt(m_hSocket,SOL_SOCKET,SO_SNDTIMEO,(char *)&nSend,sizeof(nSend));
return 0;
}
bool SetNoBlock(bool IsNoBlock=true)
{
unsigned long ul = IsNoBlock;
if (m_hSocket==INVALID_SOCKET)
return false;
if (SOCKET_ERROR==ioctlsocket(m_hSocket, FIONBIO, (unsigned long*)&ul))
return false;
return true;
}
bool SetRecvBuf(int nSize)
{
int nLen=sizeof(int);
setsockopt(m_hSocket, SOL_SOCKET,SO_RCVBUF,(char *)&nSize,nLen);
return true;
}
void Clean()
{
static BYTE byData[128];
if (m_hSocket==INVALID_SOCKET)
return ;
SetNoBlock();//改成非阻塞状态
int nRet(1);
UINT pRecLen;
while(nRet>0)
nRet=Recv(byData,&pRecLen,-1,128-2);
SetNoBlock(false);//改成阻塞状态
}
};