简体   繁体   中英

Server sent event sends data repeatedly

I'm a student and i'm doing a project for a social trading platform. I would like to implement a notification system and i think SSE is a good idea. However, my SSE code sends data repeatedly for some reason (i only want to send once). Im running these scripts on XAMMP APACHE in localhost.

SSE sse.php

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
function sendMsg($id, $msg) {
  echo "id: $id" . PHP_EOL;
  echo "data: $msg" . PHP_EOL;
  echo PHP_EOL;
  ob_flush();
  flush();
}
$serverTime = time();
sendMsg($serverTime, 'server time: ' . date("h:i:s", time()));
?>

Client financials.php

<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>

<script>
if(typeof(EventSource)!=="undefined")
  {
  var source=new EventSource("sse.php");
  source.onmessage=function(event)
    {
    document.getElementById("result").innerHTML+=event.data + "<br>";
    };
  }
else
  {
  document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
  }
</script>

</body>
</html>

Thanks in advance for any help rendered :).

SSE is designed to send messages repeatedly (say, the connection will always be open unless you call close method).

Server-Sent Events (SSE) are aa part of the HTML5 specification. SSE allows a uni-directional persistent connection between a client and server, such that the client makes only a single request and the server keeps pushing data to the client continuously, until the connection is closed.

The frequency can be set through the retry field. For detailed information, you can check it out HERE .

In a previous project of mine, I made use of the id field to uniquely identify an event. When the client received the event, check whether the event had been handled. If not, handle it. Otherwise, ignore it. You can set the fields by:

echo "retry: xx"
echo "id: xx"

However, since you want to make a trading system, I do not think SSE is a good idea. From my perspective, SSE is good for massively spread messages instead of send message to a specific client. I recommend web socket.

BTW: never forget the trailing '\\n'...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM