Server Sent Event Does Not Maintain Open Connection
I’ve been working with some example code that I found on the web to get some basic server sent events working on our server, but I’ve stumbled across some strange behavior when testing across servers. Below is the function being called in my controller:
public function hi() {
header("Content-Type: text/event-stream\n\n");
$counter = rand(1, 10);
while (1) {
// Every two seconds, send a "ping" event.
echo "event: ping\n";
$curDate = date(DATE_ISO8601);
echo 'data: {"time": "' . $curDate . '"}';
echo "\n\n";
ob_flush();
flush();
sleep(2);
}
}
My View:
<script>
var evtSource = new EventSource("picks/hi");
evtSource.onmessage = function(e) {
console.log(e.data);
}
evtSource.onerror = function(e) {
console.log("EventSource failed.");
};
evtSource.onopen = function(e) {
console.log("Connection open");
};
evtSource.addEventListener("ping", function(e) {
var newElement = document.createElement("li");
var obj = JSON.parse(e.data);
console.log(obj.time);
}, false);
</script>
Now here’s the bizarre part. This code works as it should on my hostgator account. It opens a connection, maintains it, and spits out the time every two seconds. If you view the console in Chrome, you will see the following output:
Connection open
2014-04-02T15:10:24-0400
{"time": "2014-04-02T15:10:26-0400"}
{"time": "2014-04-02T15:10:28-0400"}
{"time": "2014-04-02T15:10:30-0400"}
{"time": "2014-04-02T15:10:32-0400"}
{"time": "2014-04-02T15:10:34-0400"}
{"time": "2014-04-02T15:10:36-0400"}
{"time": "2014-04-02T15:10:38-0400"}
Unfortunately, this same block of code does not work on our server through Amazon Web Services. When I use the console to compare what is going on between the two, I can see that the code on the hostgator server does indeed open and maintain a persistent connection. When I do the same on the AWS instance, I see that the GET request for data is stuck in a pending status. I believe this is an apache issue, but I cannot find any information. What do I need to do on the server side to enable server sent events to properly function?