PHP code example of iphper / event-source

1. Go to this page and download the library: Download iphper/event-source 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/ */

    

iphper / event-source example snippets


use EventSource\EventSource;

$eventSource = new EventSource(3, '新消息123456789');
while(true) {
    // $eventSource->write(); // write与json方法仅对非string类型数据进行json格式化
    // 不传参数时,会直接发送构造方法中的'新消息123456789'; 若构造方法也没传则发送空串
    $eventSource->json([
        'message' => '消息'.random_int(1, 1000),
        'time' => time()
    ]);
    // 判断是否关闭连接
    if ($eventSource->reborted()) {
        break;
    }
    sleep(1);
}


use EventSource\SwooleEventSource;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Http\Server;
use Swoole\Coroutine;


$http = new Server('0.0.0.0', 18088);
$http->on('request', function (Request $request, Response $response) {

    if ($request->server['path_info'] == '/favicon.ico' || $request->server['request_uri'] == '/favicon.ico') {
        $response->end();
        return;
    }
    echo 'path:', $request->server['request_uri'],PHP_EOL;

    if ($request->server['path_info'] == '/index.html') {
        $response->write(file_get_contents(__DIR__.'/index.html'));
        return;
    }

    // 使用SSE
    $sev = SwooleEventSource::make($response);

    while(true) {
        
        $sev->json([
            'message' => 'swoole消息'. rand(1, 100),
            'time' => time(),
        ]);
        $back = time() <= 1713952254;
        // 超过时间就done【代表发送完毕】
        $back or $sev->done();

        if ($sev->aborted()) {
            // 客户端应当对stop事件进行监听处理
            $sev->write('结束了', 'stop');
            break;
        }

        Coroutine::sleep(1);
    }
});
$http->start();