Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server Sent Events PHP blocking flow

i dont know if its a problem but, im doing a feed from php to javascript using Server Sent events instead of ajax. All work fine except that, sleep on server side, keeps event source blocking webpage flow. I did a pretty simple code to test, and i got the same results.

I will put the code above.

Server sent events hangs the page flow? its not like ajax thats do a async requests?

The main question is: Server sent events hangs code flow, what i mean is, the page waits for EventSource to keep code execution, every time eventSouce opens a connection or receive a message. I can see this clear when i put a sleep on server side code, my page stops for the sleep time, run for 3 seconds, then hangs again. When i do an ajax call, the call is async, so the code keeps running with ajax in background, even if i put a sleep on server side. I hope can you understand now =p

test.php

                    @set_time_limit(0);
                    //send the proper header
                    header('Content-Type: text/event-stream');
                    header('Cache-Control: no-cache');
                    if(function_exists('apache_setenv')){
                        @apache_setenv('no-gzip',1);
                    }
                    @ini_set('zlib.output_compression',0);
                    @ini_set('implicit_flush',1);
                    for($i = 0; $i < ob_get_level(); $i++){
                        ob_end_flush();
                    }
                    ob_implicit_flush(1);

                $startedAt = time();

                do {

              $time = time();
              echo "id: $startedAt " . PHP_EOL;
              echo "data: {\n";
              echo "data: \"msg\": \"$time\", \n";
              echo "data: \"id\": $startedAt\n";
              echo "data: }\n";
              echo PHP_EOL;
                //@ob_flush();
                @ob_end_flush();
                @flush();   
                usleep(0.5*1000000);
                } while(true);

HTML

if(!!window.EventSource) {
     var source = new EventSource('test.php');
     source.addEventListener('open', function(event) {
     console.log('open');
  }, false);
    source.addEventListener('message', function(event) {
    var data = JSON.parse(event.data);  
    console.log(event.data);
  },false);
}
like image 890
Daniel Echizen Avatar asked Aug 07 '14 15:08

Daniel Echizen


1 Answers

As Daniel answered himself, the problem could be with session lock.

session_write_close(); 

solved my problem too.

like image 119
Lukas Jelinek Avatar answered Nov 11 '22 10:11

Lukas Jelinek