0

I need to listen 2 web socket URLs in real-time together. I create 2 connect to different URLs, but I see only the first message results. How can I get messages from wss://exalpme2 without close first connect? My code example

    \Ratchet\Client\connect('wss://exalpme1')->then(function($conn) {
        $conn->on('message', function($msg) use ($conn) {
            echo "Received: {$msg}\n";
        });
    }, function ($e) {
        echo "Could not connect: {$e->getMessage()}\n";
    });

    \Ratchet\Client\connect('wss://exalpme2')->then(function($conn) {
        $conn->on('message', function($msg) use ($conn) {
            echo "Received: {$msg}\n";
        });
    }, function ($e) {
        echo "Could not connect: {$e->getMessage()}\n";
    });
Alex
  • 1

1 Answers1

2

I'm on the ReactPHP core team. It looks like you picked the simple example at the top of the readme. That's fine for when you only open one connection, but in your case you want more than that. At the bottom of the readme is a bit more advanced example but that's overkill for this. Consider the following bit of code that does the following things.

  • It uses a shared event loop instead of creating one in the helper function
  • Opens two websocket connections
  • Shows when errors happen on those connections
  • Shows when those connections close
  • Start the event loop
require __DIR__ . '/vendor/autoload.php';

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

$connector('wss://exalpme1')->then(function($conn) {
    $conn->on('message', function($msg) use ($conn) {
        echo "Received: {$msg}\n";
    });
    $conn->on('error', function(\Throwable $t) {
        echo $t;
    });
    $conn->on('close', function($code = null, $reason = null) {
        echo "Connection closed ({$code} - {$reason})\n";
    });
}, function ($e) {
    echo "Could not connect: {$e->getMessage()}\n";
});
$connector('wss://exalpme1')->then(function($conn) {
    $conn->on('message', function($msg) use ($conn) {
        echo "Received: {$msg}\n";
    });
    $conn->on('error', function(\Throwable $t) {
        echo $t;
    });
    $conn->on('close', function($code = null, $reason = null) {
        echo "Connection closed ({$code} - {$reason})\n";
    });
}, function ($e) {
    echo "Could not connect: {$e->getMessage()}\n";
});


$loop->run();
WyriHaximus
  • 1,000
  • 6
  • 8
  • Thanks for the code. How do i forward some received msgs from first connection to the 2nd one? Somethinglike(conn2.send(conn1.received).. – avar May 04 '23 at 16:49