leocavalcante / siler

⚡ Flat-files and plain-old PHP functions rockin'on as a set of general purpose high-level abstractions.
https://siler.leocavalcante.dev
MIT License
1.12k stars 90 forks source link

Server Sent Events using HTTP Server #325

Open ljfreelancer88 opened 4 years ago

ljfreelancer88 commented 4 years ago

Hi, I checked all the examples here https://github.com/leocavalcante/siler/tree/master/examples but I haven't seen any Server Sent Events using HTTP Server using Siler. Basically, what I want to do is mentioned here https://github.com/swoole/swoole-src/issues/3377. It's a simple PUB/SUB for real-time messaging like chat support and group chat.

Thank you in advance.

leocavalcante commented 4 years ago

Can I ask you: why SSE instead of WebSockets?

ljfreelancer88 commented 4 years ago

Because of the re-reconnect capability if the connection was dropped, it doesn't use the "custom" protocol, I want to take advantage the HTTP/2 & HTTP/3 push server feature. I think it's easy to switch to any protocol for testing unlike WebSocket+HTTP/2, WebSocket+HTTP/3 which is still in draft mode.

leocavalcante commented 4 years ago

Ok, well, I haven't my self tried to implement something with SSE, but I will trying when have time. I already warn you that this is low priority, sorry, there are another issues I'd like to close first.

Have you already tried something already? There was errors?

ljfreelancer88 commented 4 years ago

Yes, I've tried it but I encountered errors. Frustrating because of the Swoole documentation is not that clear.

In PHP(No Swoole), I basically wrapped with do while loop to control the default behaviour(keeps publishing events every 5sec.) of Server Sent Events. But when I implement the do while loop in Swoole I encountered error regarding detached. I'm hoping I can fix the issue using existing tool like Siler.

Here is my code by the way

$http->on('request', function ($request, $response) use ($messages, $http) {
    $response->header('Content-Type', 'text/event-stream');
    $response->header('Cache-Control', 'no-cache');
    $response->header('Connection', 'keep-alive');
    $response->header('X-Accel-Buffering', 'no');

    $startTime = time();
    $maxExecution = ini_get('max_execution_time');

    go(function() use ($response, $request, $startTime, $maxExecution, $http, $messages) {
        if (connection_aborted()) {
            //how to exit in swoole way?
        }

        if (connection_status() !== 0) {
            //how to exit in swoole way?
        }

        if (time() >= $startTime + $maxExecution) {
            //how to exit in swoole way
        }

        $l = isset($request->get['event']) ? $request->get['event'] : 'wala';

        $date = date('H:i:s');
        $echo = emitter(null, ['time' => $date . $l]);        

        $response->end($echo);

        co::sleep(2);
    });
});