Search code examples
phpstomp

PHP:Stomp - Is it possible to catch errors on "send()"?


I'm using the PHP Stomp client to send a stomp message.

I would like to leave a persistent connection open, in the background, and send messages occasionally.

However, I can't find a way to handle connection errors if they happen after opening the connection (on send()).

For example, when running:

<?php
$stomp = new Stomp('tcp://localhost:61613');

sleep(5); // Connection goes down in the meantime

$result = $stomp->send('/topic/test', 'TEST');

print "send " . ($result ? "successful\n": "failed\n");
?>

Output: send successful

Even if the connection goes down while in sleep(), send() always returns true.

The docs weren't very helpful, Stomp::error() and stomp_connect_error() also don't help much as they return false.

As a temporary solution, I'm reconnecting before every send().

Is there a better way to catch connection errors?


Solution

  • Found the answer in the specification of the stomp protocol itself:

    Any client frame other than CONNECT MAY specify a receipt header with an arbitrary value. This will cause the server to acknowledge receipt of the frame with a RECEIPT frame which contains the value of this header as the value of the receipt-id header in the RECEIPT frame.

    So setting a "receipt" header makes the request synchronous, so the connection to the server must be alive.

    So the code:

    $result = $stomp->send('/topic/test', 'TEST');
    print "send " . ($result ? "successful\n": "failed\n");
    
    $result = $stomp->send('/topic/test', 'TEST', array('receipt' => 'message-123'));
    print "send " . ($result ? "successful\n": "failed\n");
    

    Gives output:

    send successful
    send failed
    

    It doesn't seem like the best solution for this case, but it works for me.

    If anyone knows a better way I'll be happy to hear it.


    Update:

    Eventually I switched to Stomp-PHP (a pure PHP client) instead of the Pecl stomp client, which handles it much better.