Servent-Sent events (2/2)
Code examples for presentation server-sent events
Run via nginx
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Server-Sent events</title>
</head>
<body>
<script type="text/javascript">
function retryEventSource() {
var source = new EventSource("/stream.php");
source.addEventListener('message', function (e) {
document.body.innerHTML += e.data + '<br/>';
console.log('message', e, source.readyState)
}, false);
source.addEventListener('open', function(e) {
document.body.innerHTML += '<b>OPEN</b><br/>';
console.log('open', e, source.readyState)
}, false);
source.addEventListener('error', function(e) {
console.log('error', e, source.readyState)
if (source.readyState == EventSource.CONNECTING) {
document.body.innerHTML += '<b>RECONNECTING</b><br/>';
} else {
document.body.innerHTML += '<b>ERROR</b><br/>';
source.close();
retryEventSource();
}
}, false);
}
retryEventSource();
</script>
Welcome to<br/>
</body>
</html>
server {
listen 80;
server_name php-test.local;
index index.php index.html;
root /releases/php_test/data;
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass php_test:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_buffering off;
fastcgi_cache off;
fastcgi_read_timeout 4;
}
}
server {
listen 443 ssl http2;
server_name php-test.local;
ssl_certificate "/etc/letsencrypt/live/php-test.local/fullchain.pem";
ssl_certificate_key "/etc/letsencrypt/live/php-test.local/privkey.pem";
ssl_buffer_size 1;
index index.php index.html;
root /releases/php_test/data;
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass php_test:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_buffering off;
fastcgi_cache off;
fastcgi_read_timeout 4;
}
}
<?php
header('Content-type: text/event-stream');
for ($i = 0; $i < 10; $i++) {
foreach (['VilniusPHP', 'VilniusJs'] as $event) {
print 'data: ' . $event."\n\n";
// print "\n\n";
ob_flush();
flush();
usleep(1000000);
}
}