Skip to content

Instantly share code, notes, and snippets.

@TsuiAnthonYVR
Created May 17, 2018 03:54
Show Gist options
  • Save TsuiAnthonYVR/dec0010e7f4f27f5c98c5df9e2eb18ed to your computer and use it in GitHub Desktop.
Save TsuiAnthonYVR/dec0010e7f4f27f5c98c5df9e2eb18ed to your computer and use it in GitHub Desktop.
Consuming a WebSocket API inside synchronous code
<?php
namespace App;
use React\EventLoop\Factory;
use React\Socket\Connector as SocketConnector;
use Ratchet\Client\Connector as ClientConnector;
use Clue\React\Block;
class BluzelleService
{
public $uri;
public $uuid;
public function __construct($uri = "ws://127.0.0.1:8100", $uuid = "80174b53-2dda-49f1-9d6a-6a780d4cceca")
{
$this->uri = $uri;
$this->uuid = $uuid;
}
// Read the value of at a key,
public function read($key = "myKey")
{
// Promises run on an event loop
$loop = Factory::create();
$reactConnector = new SocketConnector($loop, [
'dns' => '8.8.8.8',
'timeout' => 10
]);
// Instantiate the Websocket client
$connector = new ClientConnector($loop, $reactConnector);
$result = "";
// We have to get the result back out the nested callback
// so we use by-ref variable $result to take it back out
$promise = $connector($this->uri)->then(function ($conn) use (&$result, $key) {
$read = [
"bzn-api" => "crud",
"cmd" => "read",
"data" => [
"key" => $key,
],
"db-uuid" => $this->uuid,
"request-id"=> 1
];
// send the message read from key
$conn->send(json_encode($read));
// setup the callback to read the result
$conn->on('message', function ($msg) use (&$result, $conn) {
$result = (string) $msg;
$conn->close();
});
});
// Clue\React\Block to wait for the above async code to run.
Block\sleep(0.1, $loop);
// The reason we can't just use the promise result is that
// the promise resolves into a connection, not the actual result I want.
Block\await($promise, $loop);
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment