title: SSE cannot maintain connection
body: <p>I want to write a realtime server log viewer and just learned about SSE. I'm confused as to how to use it properly though. I'm running a Linux server with php 5.4. I have this code right now:</p>
  
  <p>HTML + JS:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;ul id='el'&gt;&lt;/ul&gt;
      &lt;script type="text/javascript"&gt;
          var eSource = new EventSource("ssedemo.php");
          eSource.onmessage = function(event) {
              var e = document.createElement("li");
              e.innerHTML = event.data;
              document.getElementById('el').appendChild(e);
          };
      &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>PHP:</p>
  
  <pre><code>&lt;?php
  header('Content-Type: text/event-stream');
  header('Cache-Control: no-cache');
  $time = date('r');
  echo "data: The server time is: {$time}\n\n";
  ob_flush();
  flush();
  ?&gt;
  </code></pre>
  
  <p>This works, but it drops the connection after each update and the client re-establishes it every 3 seconds. I would like it to update faster. From the documentation and tutorials online, it seems that the proper way to use SSE is to wrap the server code in a loop to maintain the connection, and use <code>sleep</code> to control the update time:</p>
  
  <pre><code>&lt;?php
  header('Content-Type: text/event-stream');
  header('Cache-Control: no-cache');
  while(true) {
      $time = date('r');
      echo "data: The server time is: {$time}\n\n";
      ob_flush();
      flush();
      sleep(1);
  };
  ?&gt;
  </code></pre>
  
  <p>The problem is that this doesn't work. Whenever I introduce a loop, <code>onmessage</code> is never called on the client side. I have tried numerous examples without altering any code (<a href="https://github.com/html5rocks/www.html5rocks.com/tree/master/content/tutorials/eventsource/basics/static/demo" rel="nofollow">https://github.com/html5rocks/www.html5rocks.com/tree/master/content/tutorials/eventsource/basics/static/demo</a>), (<a href="https://developer.mozilla.org/en-US/docs/Server-sent_events/Using_server-sent_events" rel="nofollow">https://developer.mozilla.org/en-US/docs/Server-sent_events/Using_server-sent_events</a>), etc, but none of them work unless I remove the loop from the php.</p>
  
  <p>Why can't I maintain the connection? Did something change in php 5.4 that prevents this from working?</p>