您的位置 首页 php

服务端主动推送消息SSE PHP+js

1、php服务端代码

 <?php
header('X-Accel-Buffering: no');
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
set_time_limit(0); //防止超时
ob_end_clean(); //清空(擦除)缓冲区并关闭输出缓冲
ob_implicit_flush(1); //这个函数强制每当有输出的时候,即刻把输出发送到浏览器。这样就不需要每次输出(echo)后,都用flush()来发送到浏览器了
while(1) {
$time = date('Y-m-d H:i:s');
$c = "retry:1000" . PHP_EOL; //重试毫秒数
$c = "event:my_test_message" . PHP_EOL; //定义事件
$c .= "data: The server time is: {$time}" . PHP_EOL; //推送内容
echo $c . PHP_EOL;
sleep(3);
}  

2、客户端代码

 <body id="result">
</body>
<script>
var source = new EventSource("sse.php");

source.addEventListener(' message ',  function (event) {
console.log(event)
})

source.addEventListener('my_test_message', function(event) { //自定义事件回调
console.log(event)
})
</script>
  

文章来源:智云一二三科技

文章标题:服务端主动推送消息SSE PHP+js

文章地址:https://www.zhihuclub.com/77744.shtml

关于作者: 智云科技

热门文章

网站地图