dongyonglie5132 2015-04-09 14:47
浏览 93

Laravel 5:使用Server-Sent Events将消息推送到浏览器

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. "

";
                        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条回答 默认 最新

  • douzhimao8656 2015-04-09 18:21
    关注

    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) . "
    
    ";
                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.

    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配