Forum

How to implement server-sent events with php

Daniel
27 August 2015, 05:04
I'm trying to implement a simple SSE engine using php. I've got a simple php program, that uses an infinite loop polling my SQL database, that sends the events. Executing the program '/usr/bin/php livetest.php' works perfectly. The problem is when accessing it via browser javascript to Hiawatha/php-fpm, it appears to be buffering. Until it reaches a CGI timeout - and I'm not sure what to change as this should be a relatively long time for proper operation (I'd like at least 10 minutes). Restarting php-fpm can sometimes "shake things loose" and give me my output - obviously not the right solution!

If I change the php program to end after each event then it works - but results in the client constantly re-connecting. Which is a form of polling and the opposite of what SSE is supposed to be about.

Is there something simple I'm missing to implement this properly?
Hugo Leisink
27 August 2015, 07:40
You are looking for the TimeForCGI setting. But this doesn't allow you to run a CGI indefinitely. I advice to look for another approach.
Daniel
27 August 2015, 10:34
Well... TimeForCGI should let me run the script for a while...but that doesn't fix my problem of being the responses. How can i have the php be sent immediately without being buffered?

What other approach would you suggest?
Hugo Leisink
27 August 2015, 13:08
Hiawatha buffers CGI output to improve network performance. A CGI cannot influence that.

The right approach depends on what you try to achieve. But whatever you do, don't let the CGI wait and do polling. A CGI process should be a single short run which, at the end of the run, terminates. That's how the usage of web applications were designed in the first place.
This topic has been closed.