In the past, when I learned socket programming, I simply called Microsoft's API functions and seldom considered network exception handling. In actual projects, network exceptions must be considered.
Network disconnection Exception Handling: Heartbeat network heartbeat Packet
In my personal understanding, there are two ways to handle the network heartbeat packet:
Method 1: The terminal initiates the request. The server records the time point of the last packet of each terminal and periodically scans all clients. If the time difference between the scan time point and the time point of the last packet receipt is greater than the time-out time
Timeout event occurs. The server clears client information records.
Method 2: when the server initiates a request, the server periodically sends a heartbeat packet and records the number of times that the client has not responded to the request, the timeout event is deemed to have occurred. If you have not received a response for multiple times but have received a response within a certain range,
The records are cleared. If no response is received continuously, the default network exception occurs.
typedef struct tagSocketPacket{ CString tagStrDeviveID; SOCKET tagSocket; SYSTEMTIME tagRecTimer;}SocketPacket,*pSocketPacket;typedef vector<SocketPacket> vectorSocketPacket;void HeartBeat(SOCKET socket){SYSTEMTIME timer; SocketPacket socketPacket; vectorSocketPacket::iterator it; for (it = myVectorPacket.begin(); it != myVectorPacket.end(); it++) {if (socket == (*it).tagSocket){GetSystemTime(&timer);socketPacket = (*it);socketPacket.tagRecTimer = timer;myVectorPacket.erase(it); VectorPacket_insert(socketPacket); break; }}}void VectorPacket_insert(SocketPacket socketPacket){myVectorPacket.push_back(socketPacket);}BOOL IsTimeOuts(SYSTEMTIME Timer){SYSTEMTIME sysTimer;GetSystemTime(&sysTimer);DWORD times1, times2;times1 = Timer.wHour*3600+Timer.wMinute*60+Timer.wSecond;times2 = sysTimer.wHour*3600+sysTimer.wMinute*60+sysTimer.wSecond;if (times2 - times1 > TIMEOUTS){return TRUE;}return FALSE;}