PHP code example of commandstring / reactphp-sse

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

    

commandstring / reactphp-sse example snippets


# index.php


use CommandString\Sse\Channel;
use CommandString\Sse\Client;
use Psr\Http\Message\ResponseInterface;
use React\EventLoop\Loop;
use React\Http\Message\ServerRequest;
use React\Stream\ThroughStream;

") {
        $stream = new ThroughStream();
        $client = new Client($stream, $clientCount++);

        echo $clientCount . PHP_EOL;

        $channel->addClient($client);

        return new React\Http\Message\Response(
             React\Http\Message\Response::STATUS_OK,
            array(
                'Content-Type' => 'text/event-stream'
            ),
            $stream
        );
    }

    return new React\Http\Message\Response(
        React\Http\Message\Response::STATUS_OK,
        array(
            'Content-Type' => 'text/html'
        ),
        file_get_contents("index.html")
    );
}))->listen(new React\Socket\SocketServer('127.0.0.1:8000'));

Loop::addPeriodicTimer(1, function () use ($channel) {
    $channel->sendMessageToAll(mt_rand(0, 9999), "item");
});