Laravel 5: Use Server-Sent Events to push messages to browser

我的梦境 提交于 2020-01-12 06:00:43

问题


I've looked at This SO question and This article to try and implement Server-Sent Events in Laravel 5. Though, between the two, I can't figure how push updates to the client based on an event. In this case, the event is a ClientException being thrown. A ClientException in my application is caused by a user made error. When one is thrown, I want to push an update to the client that populates a universal error panel.

Here's what I have in my blade:

<script>
    var source = new EventSource("{{ route('globalmessages') }}");
    source.addEventListener("message", function(e)
    {
        $("#errors").html(e);
    }, false);
</script>

<div id="errors">
</div>

The EventSource successfully hits the the controller action:

public function pushErrors()
{
    $response = new StreamedResponse(function()
    {
        $errors = ???; // How do I populate this
        if (!empty($error))
        {
            echo $error;
            ob_flush();
            flush();
        }
        else
        {
            \Log::info("No errors to push");
        }
    });

    $response->headers->set('Content-Type', 'text/event-stream');
    return $response;
}

And the error handling happens in Handler.php@render:

if ($e instanceof ClientException)
    {
        $message = $e->getMessage(); // Need to send this to client
        return \Response::json([]);
    }
    else
    {
        return parent::render($request, $e);
    }

So, what I need to do is somehow give the errors to the controller route. I tried using a singleton, but I couldn't get that to work. I tried giving the controller a field to hold it, but that was always empty.

On top of that, this current implementation seems to be running every 5 seconds. I'd like to be able to call a function when the ClientException is thrown to push the update.

Thanks for any help.

EDIT:

Some more info:

Here's the controller action that renders my page:

class HomeController
{
    public function getHome()
    {
        return view('home');
    }
}

My controller using an infinite loop:

class MainController extends RouteController
{
    public function pushErrors()
    {
        $response = new StreamedResponse();
        $response->headers->set('Content-Type', 'text/event-stream');
        $response->headers->set('Cach-Control', 'no-cache');

        $response->setCallback(
            function()
            {
                while (true)
                {
                    $error = MessageQueue::dequeue();
                    if (!empty($error))
                    {
                        echo 'data: ' . $error. "\n\n";
                        ob_flush();
                        flush();
                    }
                    sleep(1);
                }
            });

        return $response;
    }
}

If I take out the while loop, this code works, in that the message is pushed, the connection dropped, then re-established and pushed again. With the while loop, the page just hangs.

My routes:

+--------+----------+----------------+----------------+--------------------------------------------------+------------+
| Domain | Method   | URI            | Name           | Action                                           | Middleware |
+--------+----------+----------------+----------------+--------------------------------------------------+------------+
|        | GET|HEAD | globalmessages | globalmessages | App\Http\Controllers\MainController@pushErrors   |            |
|        | GET|HEAD | /              | /              | App\Http\Controllers\HomeController@getHome      |            |
|        | POST     | login          | login          | App\Http\Controllers\HomeController@postLogin    |            |
+--------+----------+----------------+----------------+--------------------------------------------------+------------+

HomeController@postLogin is the route that I call to that generates the ClientException.


回答1:


Your controller is missing a key function from the article. In the article, the controller is doing an endless loop. In the endless loop, the data is checked for similarity, if the data has changed then the buffer is flushed and written so that the client JS can read it.

How I would implement this is to create a table that holds all your ServerSentEvents, then in my controller query from that table and retrieve the rows which have not yet been sent.

In this example, we will check if there is any data in our $data array, and send it to the client if there is.

DB::table('ServerSentEvents')->where('sent', 0)->get();

Will return a empty array if there are no rows returned from the query.

public function pushErrors() {

$response = new Symfony\Component\HttpFoundation\StreamedResponse(function() {

    $data = $this->getData();

    while (true) {
        if (!empty($data)) {
            echo 'data: ' . json_encode($data) . "\n\n";
            ob_flush();
            flush();

            /* update the table rows as sent */
            $ids = [];
            foreach($data as $event){
                $ids[] = $event->id;
            }
            DB::table('ServerSentEvents')->whereIn('id', $ids)->update('sent', 1);              
        }

        //sleep for 3 seconds
        sleep(3);

        //requery for new events that need to be sent
        $data = $this->getData();
    }

});

    $response->headers->set('Content-Type', 'text/event-stream');
    return $response;
}

public function getData(){
    $data = DB::table('ServerSentEvents')->where('sent', 0)->get();
    return $data;
}

You also need to insert new rows into your database when the ClientException occurs:

if ($e instanceof ClientException)
{
    DB::table('ServerSentEvents')->insert(['message' => $e->getMessage(), 'sent' => 0]);        
}
else
{
    return parent::render($request, $e);
}

Depending on what kind of information you want based on your events you may need to add or remove more columns to the ServerSentEvents table.

The ServerSentEvents table is a table you will need to create, I didn't provide a structure here because there may be more information you want to save in the rows, and the overall concept of pulling the data from the database is the point.



来源:https://stackoverflow.com/questions/29541775/laravel-5-use-server-sent-events-to-push-messages-to-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!