HTML5的服务器EventSource(server-sent event)发送事件

参考资料:

HTML5的服务器(server-sent event)发送事件有什么应用场景?

W3school HTML 5 服务器发送事件

『后台消息推送功能』,前端除了轮询、scoket、第三方服务(如wilddog)外,暂时没好方案。刚刚还真发现个新的了:HTML5的服务器 EventSource (server-sent event)发送事件

总体体验就是简化版的socket。并不能代替 socket ,适应场景是客户端只需要监听,不需要发送消息给服务端的情况。

目前还有一个问题:从效果上看,是3秒一次轮询。但不知道有什么API可以设定频率……

index.html

<!DOCTYPE html>
<html lang='en'>

<head>
    <meta charset='UTF-8'>
</head>

<body>
    <div id='app'></div>
</body>
<script>
const app = document.getElementById('app')
const source = new EventSource('http://localhost/SSE.php')

/**
 * EventSource 支持的事件有三种 ...
 * 
    『名称』    『说明』                      『事件处理方法』
    open     当成功与服务器建立连接时产生  onopen
    message  当收到服务器发送的事件时产生  onmessage
    error    当出现错误时产生             onerror
 */
source.onmessage = e => {
    app.innerHTML += e.data + '<br>'
}
</script>

</html>

SSE.php

<?php
header('Content-Type: text/event-stream'); 
header('Cache-Control: no-cache'); 

$time = date('r'); 

/**
 * ⚠️ 需要注意的点
 * 1. php推送的信息一个使用了”\n\n”作为结束标志。
 * 经过测试,如果不以”\n\n”作为结束标志。
 * 那么客户端将不能接收到推送的值。
 * 
 * 2. 推送的信息格式必须为"data:内容\n\n"
 */
echo "data: The server time is: {$time}\n\n"; 
flush(); 

效果图如下:

 

猜你喜欢

转载自www.cnblogs.com/CyLee/p/11440496.html
今日推荐