Long polling in the Laravel function (sleep () makes the application freeze)

I am trying to program long polling functions in Laravel, but when I use the sleep () function, the whole application freezes / locks until the sleep () function is executed. 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 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 use: PHP 5.5 and Apache 2.2.22

The problem does not occur outside of Laravel (in no Laravel project).

Thanks in advance.

+7
long-integer php apache laravel polling
source share
2 answers

This is actually a long poll if you use bonez code. A long polling is if the connection remains open (possibly with a timeout) until the server sends a response. If a client sends a request every 2 seconds and receives a response, this is just a poll and you get a server response 2 seconds later in the worst case. With a long survey, you do not have this delay.

The freeze issue is not a bug with Laravel. Session Sections. Therefore use session_write_close (); before calling the long polls method or using the cookie session driver. For more information see http://konrness.com/php5/how-to-prevent-blocking-php-requests/

+5
source share

You have to do longpolling in javascript and check every 2 seconds

 var refreshIntervalId = setInterval(function () { // perform AJAX request every 2 seconds longpending = $.ajax({ type: 'POST', url: '/getNewWords', data: { wordid: ""+$('.lastWordId').attr('class').split(' ')[1]+"" }, async: true, cache: false }).done(function(data) { // process JSON response var obj = jQuery.parseJSON(data); $("#words").prepend(obj.output); if(obj.status) == 'complete' clearInterval(refreshIntervalId); startRefresh(); }); }, 2000); // end refreshInterval 

Then in your PHP

 echo json_encode(array('status'=> 'incomplete', 'output'=>$theView)); 

Not tested this code, but you should get this idea.

-6
source share

All Articles