Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda