6
votes

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);
}
1
Could you rephrase your specific question, please?Cobra_Fast
Just for the record, i have found the problem. My problem was with session locking php from running. session_write_close() did the trick;Daniel Echizen

1 Answers

7
votes

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

session_write_close(); 

solved my problem too.