Delphi Receives Heartbeat Packet
Anyone who has developed a Web application experience knows that receiving and sending data in the network is implemented using sockets in Windows. However, if the socket is disconnected, there must be a problem when sending data and receiving data. But how can you tell if the socket is still available?
One must have thought of using the return result in the Send function to judge. If the length of the return is the same as the length you send out, it means that the socket is available, otherwise there must be a problem with the socket. But we don't send data all the while. How to solve it?
In fact, TCP has implemented a mechanism called heartbeat for us. If you set a heartbeat, TCP will send your heartbeat (say 2 times) within a certain amount of time (for example, 3 seconds), and this information will not affect your own defined protocol.
There are many examples of the realization of heartbeat in VC, but there is no corresponding code in Dlephi. Here I am using Delphi written about the heartbeat of the code (take IOCP as an example), I hope to be helpful to everyone.
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 in acceptsc:= wsaaccept (LISTENSC, nil, nil, nil, 0); Add the following code:
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 time interval
inkeepalive.keepalivetime:=3000;
Set the heartbeat that is sent 1 times 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 you add the above code, the system will add a heartbeat every 3 seconds. And if the client is disconnected (the network cable is broken), the function GetQueuedCompletionStatus returns FALSE.
if (GetQueuedCompletionStatus (Completionport, Bytestransferred,dword (Perhandledata), poverlapped (PerIoData), INFINITE) = False) Then
Begin
The client disconnection information is handled here.
Continue
End
Delphi Receives Heartbeat Packet