Search code examples
phpsocketsclientwssreactphp

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?


Solution

  • 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);
        });
    });