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

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

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能