1. typedef struct STcpKeepAlive2
2. {
3. DWORD onoff;
4. DWORD keepalivetime;
5. DWORD keepaliveinterval;
6.
7. }TCP_KEEP_ALIVE2;
8.
9. VOID SetKeepLive(SOCKET m_Socket)
10. {
11. const char chOpt = 1; // True
12. // Set KeepAlive 开启保活机制, 防止服务端产生死连接
13. if (setsockopt(m_Socket, SOL_SOCKET, SO_KEEPALIVE, (char *)&chOpt, sizeof(chOpt)) == 0)
14. {
15. // 设置超时详细信息
16. TCP_KEEP_ALIVE2 klive;
17. klive.onoff = 1; // 启用保活
18. klive.keepalivetime = 1000 * 15; // 3分钟超时 Keep Alive
19. klive.keepaliveinterval = 1000 * 5; // 重试间隔为5秒 Resend if No-Reply
20. WSAIoctl
21. (
22. m_Socket,
23. SIO_KEEPALIVE_VALS,
24. &klive,
25. sizeof(TCP_KEEP_ALIVE2),
26. NULL,
27. 0,
28. (unsigned long *)&chOpt,
29. 0,
30. NULL
31. );
32. }
33. }