HTML5 SSE学习笔记

简介

HTML5 Server-Sent Events (SSE)是一种服务器向客户端发送事件流的技术。它允许服务器通过单个HTTP连接向客户端发送任意数量的消息。客户端通过JavaScript EventSource接收这些消息。

使用方法

1. 创建EventSource对象

要接收来自服务器的事件流,需要创建一个EventSource对象。这可以通过以下方式完成:

javascriptCopy Code
var source = new EventSource('server.php');

其中,'server.php'是向事件流发送数据的服务器脚本路径。

2. 监听事件

一旦创建了EventSource对象,就可以使用addEventListener()方法监听来自服务器的事件。例如:

javascriptCopy Code
source.addEventListener('message', function(event) { // 处理服务器发送过来的消息 }, false);

此外,也可以监听其他事件,如打开连接、关闭连接和错误事件。

3. 发送数据

要向客户端发送数据,需要在服务器上创建一个SSE脚本。以下示例将每秒钟向客户端发送一个时间戳:

phpCopy Code
<?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); while (true) { echo "data: The server time is " . date('h:i:s') . "\n\n"; flush(); sleep(1); } ?>

示例

以下示例演示如何使用HTML5 SSE从服务器向客户端发送实时通知。

1. HTML

创建一个包含一个按钮的HTML页面:

htmlCopy Code
<!DOCTYPE html> <html> <head> <title>HTML5 SSE Example</title> </head> <body> <button id="notificationBtn">Get notifications</button> <script> var notificationBtn = document.getElementById('notificationBtn'); var notificationList = document.getElementById('notificationList'); notificationBtn.addEventListener('click', function() { var source = new EventSource('notifications.php'); source.addEventListener('message', function(event) { var newNotification = document.createElement('li'); newNotification.innerHTML = event.data; notificationList.appendChild(newNotification); }, false); }, false); </script> </body> </html>

2. PHP

创建一个名为'notifications.php'的PHP文件,向客户端发送通知:

phpCopy Code
<?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); $notifications = array( 'A new message has been received', 'The server is about to shut down', 'A security threat has been detected' ); while (true) { $nextNotification = $notifications[rand(0, count($notifications) - 1)]; echo "data: $nextNotification\n\n"; flush(); sleep(5); } ?>

总结

HTML5 SSE是一种非常有用的技术,允许服务器通过单个HTTP连接向客户端发送实时通知和其他事件流。此外,它还可以通过EventSource对象的简单API轻松地从客户端进行管理和操作。