hhxsv5 / php-sse

A simple and efficient library implemented HTML5's server-sent events by PHP, is used to real-time push events from server to client, and easier than Websocket, instead of AJAX request.
MIT License
426 stars 49 forks source link

Push events only when POST method kicks in #14

Closed ljfreelancer88 closed 4 years ago

ljfreelancer88 commented 4 years ago

Sorry, I have a lot of questions regarding implementing Swoole, because their documentation is not that detailed enough for newbie. Anyway, Is it possible to push the events when there's a POST method only? See pseudo code below.

if request method is POST
  Push the updated/new event 
else
  Sleep momentarily or send a SSE comment to make the connection alive 

Thank you again. You are a big help.

hhxsv5 commented 4 years ago

See Swoole\Http\Request->server.

if ($request->server['request_method'] === 'POST') {      
}

Indeed, English documentation is not detailed enough. Sometimes Google translates Chinese documentation as another way.

ljfreelancer88 commented 4 years ago

Hi, I've tried the following code below but it seems not working. It doesn't push event when I use the Curl POST.

When I submit a Curl POST it returns SSE comment :no update instead of the "news" event. While in my SSE server, it opens the connection but it does not return the "news" event when I do Curl POST.

go(function() use ($request, $response) {
    (new SSESwoole($request, $response))->start(new Update(function () {
        if (isset($request->server['request_method']) && 
            $request->server['request_method'] === 'POST') {
                $time = date('Y-m-d H:i:s');
                $news = [['id' => $time, 'title' => 'title ' . $time, 'content' => 'content ' . $time]]; // Get news from database or service.
                return json_encode(['news' => $news]);
            }
            return false;
    }, 2), 'news');
});
hhxsv5 commented 4 years ago

1.Start SSE Server php sse-swoole.php. image 2.Run Curl Client curl -XPOST -N http://127.0.0.1:5200/. image

ljfreelancer88 commented 4 years ago

Ow! the variable $request inside if statement is undefined, that's why it's not working. Here is the minor changes on the code new Update(function() use ($request)). Now it's working! Thank you so much for your help. Appreciate it.

Here is the final code for reference.

go(function() use ($request, $response) {
    (new SSESwoole($request, $response))->start(new Update(function() use ($request) {
        if ($request->server['request_method'] === 'POST') {
                $time = date('Y-m-d H:i:s');
                $news = [['id' => $time, 'title' => 'title ' . $time, 'content' => 'content ' . $time]]; // Get news from database or service.
                return json_encode(['news' => $news]);
            }
            return false;
    }, 2), 'news');
});