duan0427
duan0427
2013-09-07 22:59

服务器发送事件重复发送数据

已采纳

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 :).

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dry18813 dry18813 8年前

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

    Server-Sent Events (SSE) are a a 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 ' '...

    点赞 8 评论 复制链接分享

相关推荐