Created
February 11, 2021 12:37
-
-
Save carliedu/40981af7530c287abf6e0efb3d3277e4 to your computer and use it in GitHub Desktop.
Simple ReactPHP example using Ratchet/Pawl to acces Bitfinex Websocket API
This file contains 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 | |
use Clue\React\Sse\BufferedChannel; | |
require __DIR__ . '/vendor/autoload.php'; | |
$loop = React\EventLoop\Factory::create(); | |
// BEGINNING of eventloop | |
$channel = new BufferedChannel(); | |
$ratchetClConnector = new \Ratchet\Client\Connector($loop); | |
$URL = 'wss://api.bitfinex.com/ws/1'; | |
// Suggestion of @WyriHaximus | |
// $f = function () use (&$f) {$f();};$f(); | |
$ratchetClConnector($URL)->then(function(Ratchet\Client\WebSocket $webSocket_1) use (&$webSocket, &$channel) { | |
global $URL; | |
echo("Connected to Websocket ".$URL."\n"); | |
$webSocket = $webSocket_1; | |
$webSocket->on('message', function(\Ratchet\RFC6455\Messaging\MessageInterface $j_responseMsg) use (&$webSocket, &$channel) { | |
echo("ON MESSAGE occured\n"); | |
$o_return = json_decode($j_responseMsg); | |
$j_event = $o_return->{"event"}; | |
echo(date("G:i:s")." - Response from WSserver: [" .$j_event."]\n"); | |
}); | |
$webSocket->on('close', function($code = null, $reason = null) { | |
echo(date("G:i:s")." - ON CLOSE ".$URL." occured.\n"); | |
}); | |
echo("Pinging WSserver\n"); | |
ping_WSserver($webSocket); | |
echo(date("G:i:s")." - PING sent. ".$URL."\n"); | |
}, function(\Exception $e) use ($loop) { | |
global $URL; | |
echo("Could not connect ".$URL."\n"); | |
$loop->stop(); | |
}); | |
// END of eventloop | |
$loop->run(); | |
echo("END enventloop\n"); | |
function ping_WSserver($conn) | |
{ | |
class clMessageFrame{ | |
public $event = "ping"; | |
public $cid = 1234; | |
} | |
if(is_object($conn)) { | |
$messageFrame = new clMessageFrame(); | |
$json = json_encode($messageFrame); | |
$conn->send(json_encode($messageFrame)); | |
} else { | |
echo("WSserver not connected\n"); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bitfinex closes the connection approximately 90 seconds after there are no more requests.