网络程序容易出现死连接,连接以经无效了,但是连接状态还是ESTABLISHED状态,如何识别连接以经失效就需要使用
保活机制(心跳机制)下面是一个代码效果还是挺好的,感谢cooldiyer的资料
typedef struct STcpKeepAlive2 { DWORD onoff; DWORD keepalivetime; DWORD keepaliveinterval; }TCP_KEEP_ALIVE2; VOID SetKeepLive(SOCKET m_Socket) { const char chOpt = 1; // True // Set KeepAlive 开启保活机制, 防止服务端产生死连接 if (setsockopt(m_Socket, SOL_SOCKET, SO_KEEPALIVE, (char *)&chOpt, sizeof(chOpt)) == 0) { // 设置超时详细信息 TCP_KEEP_ALIVE2 klive; klive.onoff = 1; // 启用保活 klive.keepalivetime = 1000 * 15; // 3分钟超时 Keep Alive klive.keepaliveinterval = 1000 * 5; // 重试间隔为5秒 Resend if No-Reply WSAIoctl ( m_Socket, SIO_KEEPALIVE_VALS, &klive, sizeof(TCP_KEEP_ALIVE2), NULL, 0, (unsigned long *)&chOpt, 0, NULL ); } }