Fixing Server Side Events and Connection Aborted Issues

Server Side Events offer an easy way to push data to clients. It’s much easier to implement than websockets or another technology.

IF you stumble on the problem of connections not getting aborted, when clients closed the event resource, or if you see the data coming in chunks, you need to tweak your PHP server, or at least fix that behaviour by setting additional header.

On Nginx, with gzip compression enabled, you need at least these:

header("Content-Type: text/event-stream");
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no');

And you need to output a ping line of data, if you’re not outputting any real data, so that the connection doesn’t stay idle for too long. Then it will be closed by the server.

echo "event: ping\n",'data: {"time": "' . date(DATE_ISO8601) . '"}', "\n\n";

If you’re server still has a lot of running fpm processes, reload the php-service to get rid of them:

systemctl reload php7.4-fpm.service

Reload the Nginx server won’t help.

systemctl reload nginx.service

Leave a Reply



Categories
-->
Archives
Links