Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
detect lost internet connection via a hook
#4
(04-07-2022, 09:12 PM)kudzu Wrote: Most routers use a ping method, they simply ping a known server using ping protocol, or UDP or HTTP to a known server to see if a connection exists or not. You can do that with Indy.

I wouldn't even bother doing that much. Since the client needs to establish a connection to receive the push notifications, I would suggest simply having the client connect, send a request, read in a loop until disconnected, and reconnect and repeat if needed. If the network connection is lost, let the OS close the connection, which will fail any current/subsequent socket operation until the socket is closed. You can then catch those errors and move on. This is very easy to implement with Indy, especially in a worker thread (which you MUST use on Android anyway, as you CAN'T perform network operations on the main UI thread), eg:

Code:
while not Terminated do
begin
  try
    // connect...
  except
    // error handling...
    sleep(5000);
    Continue;
  end;

  try
    try
      // send request to begin push notifications...
      while not Terminated do
      begin
        // read and process a push notification...
      end;
    except
      // error handling...
    end;
  finally
    // disconnect...
  end;
end;

This way, the client doesn't have to care WHY the connection is lost, or WHY it is unable to (re-)connect. It just keeps trying until successful.

But, if you REALLY want to include a network status check, this approach allows you to do that, eg:

Code:
while not Terminated do
begin
  try
    if (network is not OK) then
    begin
      sleep(5000);
      Continue;
    end;
    // connect...
  except
    // error handling...
    sleep(5000);
    Continue;
  end;

  // use the connect as needed...
end;

For instance, you could have another thread that responds to OS notifications about network status changes. Or, on OSes that don't offer that, then simply poll the network status periodically. When you detect a valid network, set a boolean, or signal a TEvent, etc. When you detect a bad network, clear the boolean, or reset the TEvent, etc.

Then have the socket thread check/wait-on a valid network to be detected before attempting to open its socket connection.

Reply


Messages In This Thread
RE: detect lost internet connection via a hook - by rlebeau - 04-07-2022, 09:40 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)