How to Write a heartbeat packet received by Delphi
Anyone who has experienced network application development knows that receiving and sending data on the network are implemented using socket in windows. However, if the socket is disconnected, the data sending and receiving operations may fail. But how can I determine whether this socket can be used?
Some people must think of using the returned results in the send function for judgment. If the returned length is the same as the length sent by the user, it indicates that the socket is available. Otherwise, the socket must be faulty. But we are not sending data all the time. How can this problem be solved?
In fact, TCP has implemented a heartbeat mechanism for us. If you set a heartbeat, TCP will send the heartbeat (for example, twice) of the number of times you set within a certain period of time (for example, 3 seconds ), this information does not affect your own protocols.
There are many examples of implementing heartbeat in VC, but there is no corresponding code in dlephi. The following is the heartbeat code I wrote using Delphi (taking iocp as an example). I hope it will help you.
Define heartbeat Constants
Const
Ioc_in =$ 80000000;
Ioc_vendor = $18000000;
Ioc_out = $40000000;
Sio_keepalive_vals = ioc_in or ioc_vendor or 4;
VaR
Inkeepalive, outkeepalive: ttcp_keepalive;
The implementation code is added after acceptsc: = wsaaccept (listensc, nil, 0:
OPT: = 1;
If setsockopt (acceptsc, sol_socket, so_keepalive, @ opt, sizeof (OPT) = socket_error then
Begin
Closesocket (acceptsc );
End;
Inkeepalive. Onoff: = 1;
// Set the 3-second interval
Inkeepalive. KeepAliveTime: = 3000;
// Set the heartbeat sent once every 3 seconds
Inkeepalive. keepaliveinterval: = 1;
Insize: = sizeof (ttcp_keepalive );
Outsize: = sizeof (ttcp_keepalive );
If wsaioctl (accept, sio_keepalive_vals, @ inkeepalive, insize, @ outkeepalive, outsize, @ outbyte, nil, nil) = socket_error then
Begin
Closesocket (acceptsc );
End;
If the above Code is added, the system adds a heartbeat every 3 seconds. If the client is disconnected (the network cable is disconnected), The getqueuedcompletionstatus function returns false.
If (getqueuedcompletionstatus (completionport, bytestransferred, DWORD (perhandledata), poverlapped (periodata), infinite) = false) then
Begin
// Handle client disconnection information here.
Continue;
End;
The above is my Method of Using Heartbeat, which I have used in my online games. Stability!