Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
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?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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);
    });
});
about 4 years ago · Santiago Trujillo Report

0

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();
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!