Skip to content

How to send a ping every x seconds? #89

Open

Description

@chrispri

I use the gardena websocket (smart API) which closes the connection every 200 seconds even I send no ping message.
How can I get this work?

Activity

  1. changed the title [-]How go send a ping every x seconds?[/-] [+]How to send a ping every x seconds?[/+] on Jun 26, 2020
  2. sirn-se commented on Jun 26, 2020

    @sirn-se
    Contributor

    Second parameter in send() is opcode. When sending ping, the text message doesn't matter.

    $client->send('Ping message', 'ping');
  3. chrispri commented on Jun 26, 2020

    @chrispri
    Author

    Second parameter in send() is opcode. When sending ping, the text message doesn't matter.

    $client->send('Ping message', 'ping');
    

    Thanks for answer.
    But this isn´t possible when I am receiving data without async? Am I wrong?

  4. sirn-se commented on Jun 26, 2020

    @sirn-se
    Contributor

    Correct, the receive() operation is blocking. So if you are waiting for input but the server doesn't write anything for 200 seconds the connection will close.

  5. chrispri commented on Jun 26, 2020

    @chrispri
    Author

    Thats bad.
    Do you have any ideas how i can get this work?

    Here is the manual of Gardena/Husquvarna: https://developer.husqvarnagroup.cloud/apis/GARDENA+smart+system+API#/readme

    And thats the text part which makes problems:
    Make a WebSocket connection using the obtained URL. Since the WebSocket is closed automatically after 300 seconds of inactivity, we recommend sending ping messages every 150 seconds to keep the connection open.

  6. sirn-se commented on Jun 26, 2020

    @sirn-se
    Contributor

    Only thing to do is to expect socket to close and have it re-connect. As that API allows http-requests as well it should not be a problem.

    I will consider this use case for further development, though.

  7. apeman76 commented on May 10, 2021

    @apeman76

    What about this:

    	$client = new WebSocket\Client("wss://URL", [
    		'timeout' => 5
    	]);
    	$lastSend = round(microtime(true) * 1000);
    	while (true) {
    		try {
    			$time = round(microtime(true) * 1000);
    			if ($time > $lastSend + 4.9 * 1000) {
    				$lastSend = round(microtime(true) * 1000);
    				$client->send('ping', 'ping');
    			}
    			$data = $client->receive();
    			if ($data) {
    				print_r($data);
    			}
    		} catch (\WebSocket\ConnectionException $e) {
    			print_r($e);
    		}
    	}
    	$client->close();```
    
  8. chrispri commented on May 11, 2021

    @chrispri
    Author

    @mrsnut
    I tried a similar code but this can't work because the server doesn't send data the most time.
    So the while loop stops at "$data = $client->receive();" until the timeout closes the connection.

  9. marcroberts commented on Jun 14, 2021

    @marcroberts
    Contributor

    I've just opened a PR that helps with this - #140

  10. amazesecurity-dev commented on Oct 9, 2022

    @amazesecurity-dev

    I found an easier method. When you set up the client, set a timeout for the connection (one of the options parameters), like this:
    $client = new \WebSocket\Client(getenv('WS_REALTIME_URL_SPOT'), ['timeout' => 20]);

    After that, in the catch where all the websocket errors are caught, you will get a timeout after not receiving data, every 20 seconds. Use this timeout to send a heartbeat.

    } catch (\WebSocket\ConnectionException $e) {
            $dateStartPlusOneMinute = Carbon::now()->addSeconds(70);
            if ($e->getMessage() == "Client read timeout") {
                   $client->text('{"op":"ping"}');
            } else {
                   Log::info("Foutmelding: ".$e->getMessage());
            }
    }
    
  11. Cadkey commented on Jun 30, 2025

    @Cadkey

    I found an easier method. When you set up the client, set a timeout for the connection (one of the options parameters), like this: $client = new \WebSocket\Client(getenv('WS_REALTIME_URL_SPOT'), ['timeout' => 20]);

    After that, in the catch where all the websocket errors are caught, you will get a timeout after not receiving data, every 20 seconds. Use this timeout to send a heartbeat.

    } catch (\WebSocket\ConnectionException $e) {
            $dateStartPlusOneMinute = Carbon::now()->addSeconds(70);
            if ($e->getMessage() == "Client read timeout") {
                   $client->text('{"op":"ping"}');
            } else {
                   Log::info("Foutmelding: ".$e->getMessage());
            }
    }
    

    Hello, does this solution work?

  12. sirn-se commented on Jun 30, 2025

    @sirn-se
    Contributor

    @Cadkey Short answer, no.

    The use case for ping is to tell the server not to close a connection due to inactivity.
    But example code is sent after a read timeout, which is not the same thing. Neither does is send a ping as specified by websocket protocol.

    First of all, I've continued this repo as phrity/websocket (textual repo is abandoned).

    With later versions you can simply add the PingInterval middleware to activate ping mechanism.

  13. Cadkey commented on Jun 30, 2025

    @Cadkey

    @sirn-se
    Thanks.
    I'm using version 3.5.0, and I didn't see that I was on the old github, sorry.
    I followed the link and so I have to add $client->addMiddleware(new WebSocket\Middleware\PingInterval(interval: 10));
    Last question: With the standard server settings, what 'interval' value should I use to avoid disconnections? Is 10 optimized?
    Thanks for your help.

  14. sirn-se commented on Jun 30, 2025

    @sirn-se
    Contributor

    @Cadkey By default the interval will be the same as client timeout, which in turn defaults to 60 seconds.

    But it depends on the server you're connecting to. The ping-interval should be somewhat lower than the server. If server documentation do not specify timeout you'll need to try some values, and if you get timeout then lower the value.

  15. Cadkey commented on Jul 1, 2025

    @Cadkey

    @sirn-se
    So I get this exception with the message Connection operation timeout
    which I capture with:

    catch (WebSocket\Exception\ConnectionTimeoutException $e)
    {
    echo date('H:i:s ').' ERROR '.$e->getMessage()."\n";
    goto connection;
    }

    I got the error three times, and the script restarted each time.
    Before each restart, my PHP decrements the value of PingInterval($x) until this exception no longer occurs.
    My problem should be resolved soon with the correct value of $x.
    WebSocket is so much more efficient than making multiple API requests.

    Thanks for your help and for this websocket

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions