From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../eventsource/close/index.html | 138 +++++++++++++++ .../eventsource/eventsource/index.html | 149 ++++++++++++++++ .../server-sent_events/eventsource/index.html | 155 +++++++++++++++++ .../eventsource/onerror/index.html | 122 +++++++++++++ .../eventsource/onopen/index.html | 123 +++++++++++++ files/zh-cn/server-sent_events/index.html | 77 +++++++++ .../using_server-sent_events/index.html | 190 +++++++++++++++++++++ 7 files changed, 954 insertions(+) create mode 100644 files/zh-cn/server-sent_events/eventsource/close/index.html create mode 100644 files/zh-cn/server-sent_events/eventsource/eventsource/index.html create mode 100644 files/zh-cn/server-sent_events/eventsource/index.html create mode 100644 files/zh-cn/server-sent_events/eventsource/onerror/index.html create mode 100644 files/zh-cn/server-sent_events/eventsource/onopen/index.html create mode 100644 files/zh-cn/server-sent_events/index.html create mode 100644 files/zh-cn/server-sent_events/using_server-sent_events/index.html (limited to 'files/zh-cn/server-sent_events') diff --git a/files/zh-cn/server-sent_events/eventsource/close/index.html b/files/zh-cn/server-sent_events/eventsource/close/index.html new file mode 100644 index 0000000000..3b8af5d6d3 --- /dev/null +++ b/files/zh-cn/server-sent_events/eventsource/close/index.html @@ -0,0 +1,138 @@ +--- +title: EventSource.close() +slug: Server-sent_events/EventSource/close +translation_of: Web/API/EventSource/close +--- +
{{APIRef('WebSockets API')}}
+ +
 
+ +

{{domxref("EventSource")}} 的方法close()用于关闭当前的连接,如果调用了此方法,则会将{{domxref("EventSource.readyState")}}这个属性值设置为 2 (closed)

+ +
+

Note: 如果连接已经被关闭,此方法不会做任何事情

+
+ +

语法

+ +
eventSource.close();
+ +

参数

+ +

None.

+ +

返回值

+ +

Void.

+ +

例子

+ +
var button = document.querySelector('button');
+var evtSource = new EventSource('sse.php');
+
+button.onclick = function() {
+  console.log('Connection closed');
+  evtSource.close();
+}
+
+ +
+

Note: 你可以在Github上查看这整个例子: Simple SSE demo using PHP.

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "comms.html#dom-eventsource-close", "close()")}}{{Spec2('HTML WHATWG')}}Initial definition
+ + + +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
EventSource support6{{CompatNo}}{{CompatGeckoDesktop("6.0")}}{{CompatNo}}{{CompatVersionUnknown}}5
Available in shared and dedicated workers[1]{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
EventSource support4.445{{CompatNo}}124.1
Available in shared and dedicated workers[1]{{CompatVersionUnknown}}{{CompatGeckoMobile("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] But not service workers as yet.

+ +

相关链接

+ + diff --git a/files/zh-cn/server-sent_events/eventsource/eventsource/index.html b/files/zh-cn/server-sent_events/eventsource/eventsource/index.html new file mode 100644 index 0000000000..a93b5eb8b2 --- /dev/null +++ b/files/zh-cn/server-sent_events/eventsource/eventsource/index.html @@ -0,0 +1,149 @@ +--- +title: EventSource() +slug: Server-sent_events/EventSource/EventSource +tags: + - API + - EventSource + - Server-sent events +translation_of: Web/API/EventSource/EventSource +--- +

{{APIRef('WebSockets API')}}

+ +

EventSource() 构造函数返回一个新建的{{domxref("EventSource")}},它代表了一个远程资源。

+ +

语法

+ +
pc = new EventSource(url, configuration);
+ +

参数

+ +
+
url
+
 一个{{domxref("USVString")}} ,它代表远程资源的位置
+
configuration {{optional_inline}}
+
为配置新连接提供选项。可选项是: +
    +
  • withCredentials,默认为 false,指示 CORS 是否应包含凭据( credentials )。
  • +
+
+
+ +

返回值

+ +

 一个新建的 {{domxref("EventSource")}} 对象,如果指定了configuration, 则按其配置;否则,配置为合适的基本默认值。

+ + + +

示例

+ + + +
var evtSource = new EventSource('sse.php');
+var eventList = document.querySelector('ul');
+
+evtSource.onmessage = function(e) {
+  var newElement = document.createElement("li");
+
+  newElement.textContent = "message: " + e.data;
+  eventList.appendChild(newElement);
+}
+ +
+

笔记: 你可以在 GitHub 查看完整示例 — 请查看 Simple SSE demo using PHP.

+
+ + + + + +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "comms.html#dom-eventsource", "EventSource()")}}{{Spec2('HTML WHATWG')}}Initial definition
+ + + +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
 Basic support9{{ CompatGeckoDesktop("6.0") }}{{CompatUnknown}}115
CORS support (withCredentials)26{{ CompatGeckoDesktop("11.0") }}{{CompatUnknown}}12{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatAndroid("4.4") }}{{ CompatGeckoMobile("6.0") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
CORS support (withCredentials){{CompatUnknown}}{{ CompatGeckoMobile("11.0") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/server-sent_events/eventsource/index.html b/files/zh-cn/server-sent_events/eventsource/index.html new file mode 100644 index 0000000000..977bf56d90 --- /dev/null +++ b/files/zh-cn/server-sent_events/eventsource/index.html @@ -0,0 +1,155 @@ +--- +title: EventSource +slug: Server-sent_events/EventSource +tags: + - API + - Server-sent events + - 参考 +translation_of: Web/API/EventSource +--- +

{{APIRef("Websockets API")}}

+ +

EventSource 是服务器推送的一个网络事件接口。一个EventSource实例会对HTTP服务开启一个持久化的连接,以text/event-stream 格式发送事件, 会一直保持开启直到被要求关闭。

+ +

一旦连接开启,来自服务端传入的消息会以事件的形式分发至你代码中。如果接收消息中有一个事件字段,触发的事件与事件字段的值相同。如果没有事件字段存在,则将触发通用事件。

+ +

与 WebSockets,不同的是,服务端推送是单向的。数据信息被单向从服务端到客户端分发. 当不需要以消息形式将数据从客户端发送到服务器时,这使它们成为绝佳的选择。例如,对于处理社交媒体状态更新,新闻提要或将数据传递到客户端存储机制(如IndexedDB或Web存储)之类的,EventSource无疑是一个有效方案。

+ +

构造函数

+ +
+
{{domxref("EventSource.EventSource", "EventSource()")}}
+
以指定的 {{domxref("USVString")}} 创建一个新的 EventSource
+
+ +

属性

+ +

此接口从其父接口 {{domxref("EventTarget")}} 继承属性。

+ +
+
{{domxref("EventSource.onerror")}}
+
是一个 {{domxref("EventHandler")}},当发生错误时被调用,并且在此对象上派发 {{event("error")}} 事件。
+
{{domxref("EventSource.onmessage")}}
+
是一个 {{domxref("EventHandler")}},当收到一个 {{event("message")}} 事件,即消息来自源头时被调用。
+
{{domxref("EventSource.onopen")}}
+
是一个 {{domxref("EventHandler")}},当收到一个 {{event(" open ")}} 事件,即连接刚打开时被调用。
+
{{domxref("EventSource.readyState")}} {{readonlyinline}}
+
一个 unsigned short 值,代表连接状态。可能值是 CONNECTING (0), OPEN (1), 或者 CLOSED (2)。
+
{{domxref("EventSource.url")}} {{readonlyinline}}
+
一个{{domxref("DOMString")}},代表事件源的 URL。
+
+ +

事件接收器

+ +
+
{{domxref("EventSource.onerror")}}
+
Is an {{domxref("EventHandler")}} called when an error occurs and the {{domxref("EventSource/error_event", "error")}} event is dispatched on an EventSource object.
+
{{domxref("EventSource.onmessage")}}
+
Is an {{domxref("EventHandler")}} called when a {{domxref("EventSource/message_event", "message")}} event is received, that is when a message is coming from the source.
+
{{domxref("EventSource.onopen")}}
+
Is an {{domxref("EventHandler")}} called when an {{domxref("EventSource/open_event", "open")}} event is received, that is when the connection was just opened.
+
+ +

方法

+ +

此接口从其父接口 {{domxref("EventTarget")}} 继承方法。

+ +
+
{{domxref("EventSource.close()")}}
+
如果存在,则关闭连接,并且设置 readyState 属性为 CLOSED。如果连接已经被关闭,此方法不会再进行任何操作。
+
+ +

事件

+ +
+
{{domxref("EventSource/error_event", "error")}}
+
Fired when a connection to an event source failed to open.
+
{{domxref("EventSource/message_event", "message")}}
+
Fired when data is received from an event source.
+
{{domxref("EventSource/open_event", "open")}}
+
Fired when a connection to an event source has opened.
+
+ +

Additionally, the event source itself may send messages with an event field, which will create ad-hoc events keyed to that value.

+ +

示例

+ +

In this basic example, an EventSource is created to receive unnamed events from the server; a page with the name sse.php is responsible for generating the events.

+ +
var evtSource = new EventSource('sse.php');
+var eventList = document.querySelector('ul');
+
+evtSource.onmessage = function(e) {
+  var newElement = document.createElement("li");
+
+  newElement.textContent = "message: " + e.data;
+  eventList.appendChild(newElement);
+}
+ +

Each received event causes our EventSource object's onmessage event handler to be run. It, in turn, creates a new {{HTMLElement("li")}} element and writes the message's data into it, then appends the new element to the list element already in the document.

+ +
+

Note: You can find a full example on GitHub — see Simple SSE demo using PHP.

+
+ +

To listen to named events, you'll require a listener for each type of event sent.

+ +
  const sse = new EventSource('/api/v1/sse');
+
+  /* This will listen only for events
+   * similar to the following:
+   *
+   * event: notice
+   * data: useful data
+   * id: someid
+   *
+   */
+  sse.addEventListener("notice", function(e) {
+    console.log(e.data)
+  })
+
+  /* Similarly, this will listen for events
+   * with the field `event: update`
+   */
+  sse.addEventListener("update", function(e) {
+    console.log(e.data)
+  })
+
+  /* The event "message" is a special case, as it
+   * will capture events without an event field
+   * as well as events that have the specific type
+   * `event: message` It will not trigger on any
+   * other event type.
+   */
+  sse.addEventListener("message", function(e) {
+    console.log(e.data)
+  })
+  
+ +

规范

+ + + + + + + + + + + + +
规范状态
{{SpecName('HTML WHATWG', "comms.html#the-eventsource-interface", "EventSource")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.EventSource")}}

+ +

参见

+ + diff --git a/files/zh-cn/server-sent_events/eventsource/onerror/index.html b/files/zh-cn/server-sent_events/eventsource/onerror/index.html new file mode 100644 index 0000000000..ad24259a4e --- /dev/null +++ b/files/zh-cn/server-sent_events/eventsource/onerror/index.html @@ -0,0 +1,122 @@ +--- +title: EventSource.onerror +slug: Server-sent_events/EventSource/onerror +translation_of: Web/API/EventSource/onerror +--- +
{{APIRef('WebSockets API')}}
+ +
 
+ + +

{{domxref("EventSource")}} 的属性 onerror 是当发生错误且这个错误事件({{event("error")}} )被EventSource触发时调用的一个事件处理函数({{domxref("EventHandler")}})

+ +

语法

+ +
eventSource.onerror = function
+ +

例子

+ +
evtSource.onerror = function() {
+  console.log("EventSource failed.");
+};
+ +
+

Note: 你可以在Github上查看这个完整例子: Simple SSE demo using PHP.

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "comms.html#handler-eventsource-onerror", "onerror")}}{{Spec2('HTML WHATWG')}}Initial definition
+ + + +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
EventSource support6{{CompatNo}}{{CompatGeckoDesktop("6.0")}}{{CompatNo}}{{CompatVersionUnknown}}5
Available in shared and dedicated workers[1]{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
EventSource support4.445{{CompatNo}}124.1
Available in shared and dedicated workers[1]{{CompatVersionUnknown}}{{CompatGeckoMobile("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] But not service workers as yet.

+ +

相关链接

+ + diff --git a/files/zh-cn/server-sent_events/eventsource/onopen/index.html b/files/zh-cn/server-sent_events/eventsource/onopen/index.html new file mode 100644 index 0000000000..dfc47bbf4e --- /dev/null +++ b/files/zh-cn/server-sent_events/eventsource/onopen/index.html @@ -0,0 +1,123 @@ +--- +title: EventSource.onopen +slug: Server-sent_events/EventSource/onopen +tags: + - API + - Event Handler + - EventSource +translation_of: Web/API/EventSource/onopen +--- +
{{APIRef('WebSockets API')}}
+ +

{{domxref("EventSource")}}接口的 onopen 属性是一个 {{domxref("EventHandler")}} ,它在收到{{event("open")}} 事件时被调用,在那时,连接刚被打开。

+ +

语法

+ +
eventSource.onopen = function
+ +

示例

+ +
evtSource.onopen = function() {
+  console.log("Connection to server opened.");
+};
+ +
+

注意 :你可以在 GitHub 上看到一个完整的示例— 请看 使用php的SSE(服务器发送事件)demo。

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "comms.html#handler-eventsource-onopen", "onopen")}}{{Spec2('HTML WHATWG')}}Initial definition
+ + + +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
支持EventSource6{{CompatNo}}{{CompatGeckoDesktop("6.0")}}{{CompatNo}}{{CompatVersionUnknown}}5
在共享和专用的 workers上可用[1]{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
支持EventSource4.445{{CompatNo}}124.1
在共享和专用的 workers上可用 [1]{{CompatVersionUnknown}}{{CompatGeckoMobile("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] 但 目前不能在service workers上使用.

+ +

相关链接

+ + diff --git a/files/zh-cn/server-sent_events/index.html b/files/zh-cn/server-sent_events/index.html new file mode 100644 index 0000000000..4a9d6e0630 --- /dev/null +++ b/files/zh-cn/server-sent_events/index.html @@ -0,0 +1,77 @@ +--- +title: Server-sent events +slug: Server-sent_events +tags: + - API + - NeedsTranslation + - Server-sent events + - TopicStub +translation_of: Web/API/Server-sent_events +--- +
{{DefaultAPISidebar("Server Sent Events")}}
+ +

一个网页获取新的数据通常需要发送一个请求到服务器,也就是向服务器请求的页面。使用 server-sent 事件,服务器可以在任何时刻向我们的 Web 页面推送数据和信息。这些被推送进来的信息可以在这个页面上作为 Events + data 的形式来处理。

+ +

概念与使用

+ +

可以前往我们这篇文章 《使用 “server-sent events”》 学习怎么使用 server-sent events。

+ +

接口

+ +
+
{{domxref("EventSource")}}
+
Defines all the features that handle connecting to a server, receiving events/data, errors, closing a connection, etc.
+
+ +

示例

+ + + +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', '#server-sent-events', 'Server-sent events')}}{{Spec2('HTML WHATWG')}}
+ +

参见

+ +

Tools

+ + + +

相关话题

+ + + +

其他资源

+ + diff --git a/files/zh-cn/server-sent_events/using_server-sent_events/index.html b/files/zh-cn/server-sent_events/using_server-sent_events/index.html new file mode 100644 index 0000000000..505ec19a76 --- /dev/null +++ b/files/zh-cn/server-sent_events/using_server-sent_events/index.html @@ -0,0 +1,190 @@ +--- +title: 使用服务器发送事件 +slug: Server-sent_events/Using_server-sent_events +tags: + - Advanced + - DOM + - Guide + - SSE + - Server Sent Events + - messaging + - 服务器发送事件 + - 通信 +translation_of: Web/API/Server-sent_events/Using_server-sent_events +--- +

{{DefaultAPISidebar("Server Sent Events")}}

+ +

开发一个使用服务器发送的事件的Web应用程序是很容易的。你需要在服务器上的一些代码将事件流传输到Web应用程序,但Web应用程序端的事情几乎完全相同,处理任何其他类型的事件。

+ +

在Web应用程序中使用服务器发送事件很简单.在服务器端,只需要按照一定的格式返回事件流,在客户端中,只需要为一些事件类型绑定监听函数,和处理其他普通的事件没多大区别.

+ +

从服务器接受事件

+ +

服务器发送事件API也就是EventSource接口,在你创建一个新的EventSource对象的同时,你可以指定一个接受事件的URI.例如:

+ +
const evtSource = new EventSource("ssedemo.php");
+
+ +
注:从Firefox 11开始,EventSource开始支持CORS.虽然该特性目前并不是标准,但很快会成为标准.
+ +

如果发送事件的脚本不同源,应该创建一个新的包含URL和options参数的EventSource对象。例如,假设客户端脚本在example.com上:

+ +
const evtSource = new EventSource("//api.example.com/ssedemo.php", { withCredentials: true } );
+ +

一旦你成功初始化了一个事件源,就可以对 {{event("message")}} 事件添加一个处理函数开始监听从服务器发出的消息了:

+ +
evtSource.onmessage = function(event) {
+  const newElement = document.createElement("li");
+  const eventList = document.getElementById("list");
+
+  newElement.innerHTML = "message: " + event.data;
+  eventList.appendChild(newElement);
+}
+ +

上面的代码监听了那些从服务器发送来的所有没有指定事件类型的消息(没有event字段的消息),然后把消息内容显示在页面文档中.

+ +

你也可以使用addEventListener()方法来监听其他类型的事件:

+ +
evtSource.addEventListener("ping", function(event) {
+  const newElement = document.createElement("li");
+  const time = JSON.parse(event.data).time;
+  newElement.innerHTML = "ping at " + time;
+  eventList.appendChild(newElement);
+});
+ +

这段代码也类似,只是只有在服务器发送的消息中包含一个值为"ping"的event字段的时候才会触发对应的处理函数,也就是将data字段的字段值解析为JSON数据,然后在页面上显示出所需要的内容.

+ +
+

不通过HTTP / 2使用时,SSE(server-sent events)会受到最大连接数的限制,这在打开各种选项卡时特别麻烦,因为该限制是针对每个浏览器的,并且被设置为一个非常低的数字(6)。该问题在 Chrome 和 Firefox中被标记为“无法解决”。此限制是针对每个浏览器+域的,因此这意味着您可以跨所有选项卡打开6个SSE连接到www.example1.com,并打开6个SSE连接到www.example2.com。 (来自 Stackoverflow)。使用HTTP / 2时,HTTP同一时间内的最大连接数由服务器和客户端之间协商(默认为100)。

+
+ +

服务器端如何发送事件流

+ +

服务器端发送的响应内容应该使用值为text/event-stream的MIME类型.每个通知以文本块形式发送,并以一对换行符结尾。有关事件流的格式的详细信息,请参见{{ anch("Event stream format") }}。

+ +

演示的{{Glossary("PHP")}}代码如下:

+ +
date_default_timezone_set("America/New_York");
+header("Cache-Control: no-cache");
+header("Content-Type: text/event-stream");
+
+$counter = rand(1, 10);
+while (true) {
+  // Every second, send a "ping" event.
+
+  echo "event: ping\n";
+  $curDate = date(DATE_ISO8601);
+  echo 'data: {"time": "' . $curDate . '"}';
+  echo "\n\n";
+
+  // Send a simple message at random intervals.
+
+  $counter--;
+
+  if (!$counter) {
+    echo 'data: This is a message at time ' . $curDate . "\n\n";
+    $counter = rand(1, 10);
+  }
+
+  ob_end_flush();
+  flush();
+  sleep(1);
+}
+ +

上面的代码会让服务器每隔一秒生成一个事件流并返回,其中每条消息的事件类型为"ping",数据字段都使用了JSON格式,数组字段中包含了每个事件流生成时的 ISO 8601 时间戳.而且会随机返回一些无事件类型的消息.

+ +
+

: 您可以在github上找到以上代码的完整示例—参见Simple SSE demo using PHP.

+
+ +

错误处理

+ +

当发生错误(例如请求超时或与HTTP访问控制(CORS)有关的问题), 会生成一个错误事件. 您可以通过在EventSource对象上使用onerror回调来对此采取措施:

+ +
evtSource.onerror = function(err) {
+  console.error("EventSource failed:", err);
+};
+ +

关闭事件流

+ +

默认情况下,如果客户端和服务器之间的连接关闭,则连接将重新启动。可以使用.close()方法终止连接。

+ +
evtSource.close();
+ +

事件流格式

+ +

事件流仅仅是一个简单的文本数据流,文本应该使用 UTF-8 格式的编码.每条消息后面都由一个空行作为分隔符.以冒号开头的行为注释行,会被忽略.

+ +
注:注释行可以用来防止连接超时,服务器可以定期发送一条消息注释行,以保持连接不断.
+ +

每条消息是由多个字段组成的,每个字段由字段名,一个冒号,以及字段值组成.

+ +

字段

+ +

规范中规定了下面这些字段:

+ +
+
event
+
事件类型.如果指定了该字段,则在客户端接收到该条消息时,会在当前的EventSource对象上触发一个事件,事件类型就是该字段的字段值,你可以使用addEventListener()方法在当前EventSource对象上监听任意类型的命名事件,如果该条消息没有event字段,则会触发onmessage属性上的事件处理函数.
+
data
+
消息的数据字段.如果该条消息包含多个data字段,则客户端会用换行符把它们连接成一个字符串来作为字段值.
+
id
+
事件ID,会成为当前EventSource对象的内部属性"最后一个事件ID"的属性值.
+
retry
+
一个整数值,指定了重新连接的时间(单位为毫秒),如果该字段值不是整数,则会被忽略.
+
+ +

除了上面规定的字段名,其他所有的字段名都会被忽略.

+ +
注: 如果一行文本中不包含冒号,则整行文本会被解析成为字段名,其字段值为空.
+ +

例子

+ +

未命名事件

+ +

下面的例子中发送了三条消息,第一条仅仅是个注释,因为它以冒号开头.第二条消息只包含了一个data字段,值为"some text".第三条消息包含的两个data字段会被解析成为一个字段,值为"another message\nwith two lines".其中每两条消息之间是以一个空行为分割符的.

+ +
: this is a test stream
+
+data: some text
+
+data: another message
+data: with two lines
+
+ +

命名事件

+ +

下面的事件流中包含了一些命名事件.每个事件的类型都是由event字段指定的,另外每个data字段的值可以使用JSON格式,当然也可以不是.

+ +
event: userconnect
+data: {"username": "bobby", "time": "02:33:48"}
+
+event: usermessage
+data: {"username": "bobby", "time": "02:34:11", "text": "Hi everyone."}
+
+event: userdisconnect
+data: {"username": "bobby", "time": "02:34:23"}
+
+event: usermessage
+data: {"username": "sean", "time": "02:34:36", "text": "Bye, bobby."}
+
+ +

混合两种事件

+ +

你可以在一个事件流中同时使用命名事件和未命名事件.

+ +
event: userconnect
+data: {"username": "bobby", "time": "02:33:48"}
+
+data: Here's a system message of some kind that will get used
+data: to accomplish some task.
+
+event: usermessage
+data: {"username": "bobby", "time": "02:34:11", "text": "Hi everyone."}
+
+ +

浏览器兼容性

+ + + +

{{Compat("api.EventSource")}}

-- cgit v1.2.3-54-g00ecf