PHP code example of reactphp-x / sse-middleware

1. Go to this page and download the library: Download reactphp-x/sse-middleware 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/ */

    

reactphp-x / sse-middleware example snippets




eactphpX\SseMiddleware\SseMiddleware;
use ReactphpX\SseMiddleware\ServerSentEvents;
use React\Stream\ThroughStream;
use Psr\Http\Message\ServerRequestInterface;
use React\EventLoop\Loop;

$http = new React\Http\HttpServer(function (ServerRequestInterface $request) {

    $stream = new ThroughStream();

    $timer = Loop::addPeriodicTimer(1, function () use ($stream) {
        //data for example ['event'=>'ping', 'data' => 'some thing', 'id' => 1000, 'retry' => 5000]
        $stream->write(new ServerSentEvents(['data' => date('Y-m-d H:i:s')]));
    });

    $stream->on('close', function () use ($timer) {
        Loop::cancelTimer($timer);
    });

    Loop::addTimer(10, function () use ($stream) {
        $stream->end();
    });

    return (new SseMiddleware($stream, [
        'Access-Control-Allow-Origin' => '*',
    ]))($request);
});
$socket = new React\Socket\SocketServer('0.0.0.0:8090');
$http->listen($socket);