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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。