Created
September 16, 2024 13:44
-
-
Save Sebastix/857478b161af8074a5cfc22af13be54e to your computer and use it in GitHub Desktop.
Async Guzzle request with websocket endpoint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
use GuzzleHttp\Client; | |
use GuzzleHttp\Handler\StreamHandler; | |
use GuzzleHttp\HandlerStack; | |
use Valtzu\WebSocketMiddleware\WebSocketMiddleware; | |
use Valtzu\WebSocketMiddleware\WebSocketStream; | |
require __DIR__ . '/vendor/autoload.php'; | |
/** | |
* Connect to WebSocket endpoints with Guzzle HTTP client | |
* https://github.com/valtzu/guzzle-websocket-middleware | |
* | |
* Only works with PHP >8.2 | |
* | |
* Not sure how we must use the method variable here. | |
* It's weird to use the famous Guzzle HTTP client | |
* (https://docs.guzzlephp.org/en/stable/) | |
* for doing websocket connections... | |
* | |
*/ | |
try { | |
$handlerStack = new HandlerStack(new StreamHandler()); | |
$handlerStack->push(new WebSocketMiddleware()); | |
$guzzle = new Client(['handler' => $handlerStack]); | |
// Async call | |
// TODO research what we can do with this payload array | |
$payload = []; | |
/** @var \GuzzleHttp\Psr7\Response $res */ | |
$res = $guzzle->requestAsync('GET', 'wss://nostr.sebastix.dev', $payload) | |
->then( | |
function (\GuzzleHttp\Psr7\Response $e) { | |
// Success callback. | |
//print_r($e->getBody()); | |
return $e; | |
}, | |
function (\Exception $exception) { | |
// Error callback. | |
echo 'Oh darn, we have a problem'; | |
throw $exception; | |
}, | |
) | |
->wait(); | |
if ($res !== null) { | |
// Get websocket connection. | |
$ws = $res->getBody(); | |
if ($ws->isWritable()) { | |
// TODO: do we need insert the stringified Nostr event here to write? | |
$ws->write('What shall we write?'); | |
// This will return the message from the websocket endpoint (in our case it's the Nostr relay). | |
$rr = $ws->read(100); | |
echo $rr; | |
} | |
// Close websocket connection. | |
$ws->close(); | |
} | |
// TODO: read https://gorannikolovski.com/blog/asynchronous-and-concurrent-http-requests-in-php | |
// TODO: https://docs.guzzlephp.org/en/stable/quickstart.html#concurrent-requests | |
/** | |
* We can use RelaySet as pool. In this pool (GuzzleHttp\Pool) requests are handled concurrent. | |
* This pool will handle each RequestMessage as asynchronous request. | |
* This means that each request is executed simultaneously (at the same time). | |
* So for sending multiple requests concurrently we will use promises and asynchronous requests. | |
*/ | |
} catch (Exception $e) { | |
print $e->getMessage(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment