siler icon indicating copy to clipboard operation
siler copied to clipboard

Server Sent Events using HTTP Server

Open ljfreelancer88 opened this issue 4 years ago • 4 comments

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.

ljfreelancer88 avatar Jun 11 '20 14:06 ljfreelancer88

Can I ask you: why SSE instead of WebSockets?

leocavalcante avatar Jun 11 '20 14:06 leocavalcante

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.

ljfreelancer88 avatar Jun 11 '20 15:06 ljfreelancer88

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?

leocavalcante avatar Jun 11 '20 15:06 leocavalcante

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);
    });
});

ljfreelancer88 avatar Jun 11 '20 15:06 ljfreelancer88