Laravel中的长时间轮询(sleep()函数使应用程序冻结) [英] Long polling in Laravel (sleep() function make application freeze)

查看:794
本文介绍了Laravel中的长时间轮询(sleep()函数使应用程序冻结)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Laravel中编程长轮询功能,但是当我使用sleep()函数时,整个应用程序会冻结/阻止,直到完成sleep()函数.有人知道如何解决这个问题吗?

I'm trying to program long polling functionality in Laravel, but when I use the sleep() function, the whole application freezes/blocks until the sleep() function is done. Does anyone know how to solve this problem?

我的JavaScript看起来像这样:

My javascript looks like this:

function startRefresh() {

longpending = $.ajax({
    type: 'POST',
    url: '/getNewWords',
    data: { wordid: ""+$('.lastWordId').attr('class').split(' ')[1]+"" },
    async: true,
    cache: false
}).done(function(data) {
    $("#words").prepend(data);
    startRefresh();
});

}

和PHP:

public function longPolling()
{
    $time = time();
    $wordid = Input::get('wordid');
    session_write_close();
    //set_time_limit(0);

    while((time() - $time) < 15) {
        $words = Word::take(100)->where('id', '>', $wordid)
        ->orderBy('created_at', 'desc')->get();

        if (!$words->isEmpty()) {

            $theView = View::make('words.index', ['words' => $words])->render();

            if (is_object($words[0])) {
                $theView .= '<script>
                $(".lastWordId").removeClass($(".lastWordId").attr("class")
                .split(" ")[1]).addClass("'.$words[0]->id.'");
                </script>';
            }

            return $theView;

        } else {
            sleep(2);
        }
    }
}

我正在使用: PHP 5.5和Apache 2.2.22

I'm using: PHP 5.5 and Apache 2.2.22

问题似乎不在Laravel之外发生(在所有Laravel项目中都没有).

The problem doesn't seem to occur outside Laravel (in none Laravel projects).

谢谢.

推荐答案

实际上,如果您使用bonez代码,则轮询时间不长.长轮询是在服务器发送响应之前,连接保持打开状态(可能超时).如果客户端每隔2秒发送一次请求并获得响应,则这只是轮询,而在最坏的情况下,您会延迟2秒钟收到服务器响应.进行长时间轮询后,您就不会遇到这种延迟.

Actually it is not long polling if you use bonez code. Long polling is if the connection stays opened (maybe with a timeout) until the server sends a response. If the client sends every 2 seconds a request and gets a response, it is just polling and you get the server response 2 seconds late in the worst case. With long polling you don't have this delay.

冻结问题不是Laravel的错误.会话阻塞.因此,使用session_write_close();在调用长轮询方法或使用cookie会话驱动程序之前.有关更多信息,请参见 http://konrness.com/php5/how-to-prevent- block-php-requests/

The freezing problem is no error with Laravel. The session blocks. So use session_write_close(); before calling the long polling method or use the cookie session driver. For more information please see http://konrness.com/php5/how-to-prevent-blocking-php-requests/

这篇关于Laravel中的长时间轮询(sleep()函数使应用程序冻结)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆