Long polling in Laravel (sleep() function make app

2020-07-09 10:28发布

问题:

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?

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();
});

}

And the 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);
        }
    }
}

I'm using: PHP 5.5 and Apache 2.2.22

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

Thanks in advance.

回答1:

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.

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/