LordSoldier
LordSoldier

Reputation: 33

How to reconnect a client automatically on ratchetphp?

I'm using rachetphp to create a client for an api server. But i have a problem, when my connection close, whatever the reason, i can't reconnect automatically.

here the lib i use : https://github.com/ratchetphp/Pawl

<?php

require __DIR__ . '/vendor/autoload.php';

$loop = React\EventLoop\Factory::create();
$connector = new Ratchet\Client\Connector($loop);

$connector('ws://127.0.0.1:9000', ['protocol1', 'subprotocol2'], ['Origin' => 'http://localhost'])
->then(function(Ratchet\Client\WebSocket $conn) {
    $conn->on('message', function(\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
        echo "Received: {$msg}\n";
        $conn->close();
    });

    $conn->on('close', function($code = null, $reason = null) {
        echo "Connection closed ({$code} - {$reason})\n";
    });

    $conn->send('Hello World!');
}, function(\Exception $e) use ($loop) {
    echo "Could not connect: {$e->getMessage()}\n";
    $loop->stop();
});

$loop->run();

I would like to try a reconnect every Seconds after a connection close. Any ideas?

Upvotes: 3

Views: 5283

Answers (2)

Yehosef
Yehosef

Reputation: 18657

If you have pnctl (http://php.net/manual/en/book.pcntl.php) installed, you can just change the 'close' handler to this:

$conn->on('close', function($code = null, $reason = null) {
    echo "Connection closed ({$code} - {$reason})\n";

    // restart myself
    global $argv;
    pcntl_exec($_SERVER['_'], $argv);
    exit();

}); 

For me this was simpler because I didn't already have the $loop and $connector extracted, I am just using

\Ratchet\Client\connect($ws_url, [], $headers)
    ->then(function ($conn) {
        echo "connected\n";
        ...

To handle it in multiple places, I created a little helper function that I call on those events (based on the case, I add a delay).

function restartMyself() {
  global $argv;
  pcntl_exec($_SERVER['_'], $argv);
  exit();
}

Upvotes: 0

Constantin Galbenu
Constantin Galbenu

Reputation: 17693

The idea is simple but it needs some refactoring. We must put the reconnect code in the handler that is executed when the connection is closed. In order to do that we pass the $app function inside self.

require __DIR__ . '/vendor/autoload.php';

$loop = React\EventLoop\Factory::create();
$connector = new Ratchet\Client\Connector($loop);

$app = function (Ratchet\Client\WebSocket $conn) use ($connector, $loop, &$app) {
    $conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
        echo "Received: {$msg}\n";
        $conn->close();
    });

    $conn->on('close', function ($code = null, $reason = null) use ($connector, $loop, $app) {
        echo "Connection closed ({$code} - {$reason})\n";

        //in 3 seconds the app will reconnect
        $loop->addTimer(3, function () use ($connector, $loop, $app) {
            connectToServer($connector, $loop, $app);
        });
    });

    $conn->send('Hello World!');
};

function connectToServer($connector, $loop, $app)
{
    $connector('ws://127.0.0.1:9000', ['protocol1', 'subprotocol2'], ['Origin' => 'http://localhost'])
        ->then($app, function (\Exception $e) use ($loop) {
            echo "Could not connect: {$e->getMessage()}\n";
            $loop->stop();
        });
}

connectToServer($connector, $loop, $app);

$loop->run();

The idea is that when the connection receives the close event we do a reconnect using the connectToServer function:

$conn->on('close', function ($code = null, $reason = null) use ($connector, $loop, $app) {
    echo "Connection closed ({$code} - {$reason})\n";

    //in 3 seconds the app will reconnect
    $loop->addTimer(3, function () use ($connector, $loop, $app) {
        connectToServer($connector, $loop, $app);
    });
});

Upvotes: 5

Related Questions