duan0427 2013-09-07 22:59
浏览 166
已采纳

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

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 2013-09-09 06:13
    关注

    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 ' '...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错