PHP code example of clue / reactphp-eventsource

1. Go to this page and download the library: Download clue/reactphp-eventsource library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

clue / reactphp-eventsource example snippets


$es = new Clue\React\EventSource\EventSource('https://example.com/stream.php');

$es->on('message', function (Clue\React\EventSource\MessageEvent $message) {
    $json = json_decode($message->data);
    echo $json->name . ': ' . $json->message . PHP_EOL;
});

$es = new Clue\React\EventSource\EventSource('https://example.com/stream.php');

$connector = new React\Socket\Connector([
    'dns' => '127.0.0.1',
    'tcp' => [
        'bindto' => '192.168.10.1:0'
    ],
    'tls' => [
        'verify_peer' => false,
        'verify_peer_name' => false
    ]
]);
$browser = new React\Http\Browser($connector);

$es = new Clue\React\EventSource\EventSource('https://example.com/stream.php', $browser);

$es->on('message', function (Clue\React\EventSource\MessageEvent $message) {
    // $json = json_decode($message->data);
    var_dump($message);
});

$es->on('message', function (Clue\React\EventSource\MessageEvent $message) {
    $json = json_decode($message->data);
    echo "{$json->name} is {$json->age} years old" . PHP_EOL;
});

$es->on('join', function (Clue\React\EventSource\MessageEvent $message) {
    echo $message->data . ' joined' . PHP_EOL;
});

$es->on('chat', function (Clue\React\EventSource\MessageEvent $message) {
    echo 'Message: ' . $message->data . PHP_EOL;
});

$es->on('leave', function (Clue\React\EventSource\MessageEvent $message) {
    echo $message->data . ' left' . PHP_EOL;
});

$es->on('open', function () {
    echo 'Connection opened' . PHP_EOL;
});

$redis->on('error', function (Exception $e) {
    echo 'Error: ' . $e->getMessage() . PHP_EOL;
});

$es->on('error', function (Exception $e) use ($es) {
    if ($es->readyState === Clue\React\EventSource\EventSource::CLOSED) {
        echo 'Permanent error: ' . $e->getMessage() . PHP_EOL;
    } else {
        echo 'Temporary error: ' . $e->getMessage() . PHP_EOL;
    }
});

assert($message->data === 'hello');

$json = json_decode($message->data);
assert($json->message === 'hello');

assert($message->data === 'hello');
assert($message->lastEventId === '1');

assert($message->data === 'Alice');
assert($message->type === 'join');