#include
#include
#pragma comment(lib,"ws2_32.lib")
class CLinkCheck
{
public:
static unsigned int __stdcall Check(void * pParam)
{
CLinkCheck* pThis = (CLinkCheck*)pParam;
pThis->m_nEchoCount = 0;
pThis->m_bStop = false;
while(!pThis->m_bStop)
{
if(pThis->m_nEchoCount<3)
{
pThis->SendEchoMessage();
}
else
{
//关闭指定的socket
closesocket(pThis->a);
//进行重连操作 略
pThis->m_nEchoCount = 0;
}
//10 秒钟检测一次是否需要发送心跳消息
Sleep(10 * 1000);
}
return 0;
};
void SendEchoMessage()
{
// send (a,"hello",5); 发送心跳请求消息
m_nEchoCount++;
}
void RecvEchoMessage()
{
m_nEchoCount = 0;
}
SOCKET a;
int m_nEchoCount;//心跳计数
bool m_bStop; //停止心跳线程
};
//心跳线程函数
int main()
{
HANDLE hThread;
unsigned threadID;
//创建socket 略
SOCKET a = INVALID_SOCKET;
CLinkCheck* pLinkCheck = new CLinkCheck;
pLinkCheck->a = a;
//创建心跳检测线程
hThread = (HANDLE)_beginthreadex( NULL, 0, &CLinkCheck::Check, (LPVOID)pLinkCheck, 0, &threadID );
if(hThread == NULL)
return false;
while(true)
{
Sleep(10);
}
system("pause");
return 0;
}