Answer the question
In order to leave comments, you need to log in
Server Side Events gives data all at once, not in a stream. Where is the mistake?
The problem is the following, there are 2 parts of the SSE script (on php and html + js) and when the script runs on the local machine (windows + nginx + php), it runs the entire duration of the php script and gives information at once, and not in "pieces" for stream. What could be the problem?
Whether the matter is in the PHP settings, or NGINX ..
Server code:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
function send_message($id, $message) {
echo "id: $id" . PHP_EOL;
echo "data: " . json_encode(array('message' => $message)) . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
for($i = 0; $i < 10; $i++) {
send_message($i, 'server time: ' . date("H:i:s", time()));
sleep(1);
}
send_message(0, 'CLOSE');
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script>
var source = '';
function start_task() {
source = new EventSource('1.php');
source.addEventListener('message', function(e) {
var result = JSON.parse(e.data);
add_log(result.message);
if (e.data.search('CLOSE') != -1) source.close();
});
source.addEventListener('error', function(e) {
add_log('ERROR');
source.close();
});
}
function stop_task() {
source.close();
add_log('STOPPED');
}
function add_log(message){
var r = document.getElementById('results');
r.innerHTML += message + '<br>';
r.scrollTop = r.scrollHeight;
}
</script>
</head>
<body>
<input type="button" onclick="start_task();" value="Start"> <input type="button" onclick="stop_task();" value="Stop">
<br />
Лог
<div id="results" style="height:200px; overflow:auto; background:#eee;"></div>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question