WebSocket 与服务器发送的事件/EventSource

发布于 2024-10-20 11:28:41 字数 1701 浏览 1 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

云醉月微眠 2024-10-27 11:28:41

Websockets 和 SSE(服务器发送事件)都能够将数据推送到浏览器,但它们不是竞争技术。

Websockets 连接既可以向浏览器发送数据,也可以从浏览器接收数据。可以使用 Websocket 的应用程序的一个很好的示例是聊天应用程序。

SSE 连接只能将数据推送到浏览器。在线股票报价或更新时间线或提要的 Twitter 都是可以从 SSE 中受益的应用程序的好例子。

在实践中,由于 SSE 可以完成的所有事情也可以通过 Websockets 完成,因此 Websockets 受到了更多的关注和喜爱,支持 Websockets 的浏览器也比 SSE 多得多。

然而,对于某些类型的应用程序来说,它可能有点过头了,并且使用 SSE 等协议可以更轻松地实现后端。

此外,SSE 可以仅使用 JavaScript 填充到本身不支持它的旧浏览器中。 SSE polyfill 的一些实现可以在 Modernizr github 页面 上找到。

陷阱

  • SSE 受到最大打开连接数的限制,在打开各种选项卡时可能会特别痛苦,因为该限制是针对每个浏览器的,并且设置得非常低数字(6)。该问题已在 ChromeFirefox。此限制针对每个浏览器 + 域,因此这意味着您可以跨所有选项卡打开 6 个到 www.example1.com 的 SSE 连接,以及另外 6 个到 www.example2.com 的 SSE 连接(感谢 Phate)。
  • 只有WS可以同时传输二进制数据和UTF-8,SSE仅限于UTF-8。 (感谢 Chado Nihi)。
  • 一些具有数据包检查功能的企业防火墙在处理 WebSocket 时遇到问题(Sophos XG Firewall、WatchGuard、McAfee Web Gateway)。

HTML5Rocks 有一些关于 SSE 的好信息。从该页面:

服务器发送的事件与 WebSockets

为什么您会选择服务器发送事件而不是 WebSocket?好问题。

SSE 一直处于阴影之中的一个原因是,后来的 API(例如 WebSocket)提供了更丰富的协议来执行双向、全双工通信。对于游戏、消息应用程序以及需要双向近乎实时更新的情况来说,拥有双向通道更具吸引力。然而,在某些情况下,数据不需要从客户端发送。您只需要某些服务器操作的更新。一些例子是朋友的状态更新、股票行情、新闻提要或其他自动数据推送机制(例如更新客户端 Web SQL 数据库或 IndexedDB 对象存储)。如果您需要向服务器发送数据,XMLHttpRequest 永远是您的好帮手。

SSE 通过传统的 HTTP 发送。这意味着它们不需要特殊的协议或服务器实现即可工作。另一方面,WebSocket 需要全双工连接和新的 Web Socket 服务器来处理该协议。此外,服务器发送的事件具有 WebSocket 设计上缺乏的各种功能,例如自动重新连接、事件 ID 以及发送任意事件的能力。


TLDR 摘要:

SSE 相对于 Websockets 的优点

  • 通过简单的 HTTP 而不是自定义协议进行传输
  • 可以使用 javascript 进行填充,以将 SSE“向后移植”到尚不支持它的浏览器。
  • 内置对重新连接和事件 ID 的支持
  • 更简单的协议
  • 企业防火墙执行数据包检查时不会出现问题

Websockets 相对于 SSE 的优势:

  • 实时、双向通信。
  • 更多浏览器中的本机支持

SSE 的理想用例:

  • 股票行情行情流媒体
  • Twitter feed 更新
  • 浏览器通知

SSE 问题:

  • 无二进制支持
  • 最大打开连接数限制

Websockets and SSE (Server Sent Events) are both capable of pushing data to browsers, however they are not competing technologies.

Websockets connections can both send data to the browser and receive data from the browser. A good example of an application that could use websockets is a chat application.

SSE connections can only push data to the browser. Online stock quotes, or twitters updating timeline or feed are good examples of an application that could benefit from SSE.

In practice since everything that can be done with SSE can also be done with Websockets, Websockets is getting a lot more attention and love, and many more browsers support Websockets than SSE.

However, it can be overkill for some types of application, and the backend could be easier to implement with a protocol such as SSE.

Furthermore SSE can be polyfilled into older browsers that do not support it natively using just JavaScript. Some implementations of SSE polyfills can be found on the Modernizr github page.

Gotchas:

  • SSE suffers from a limitation to the maximum number of open connections, which can be specially painful when opening various tabs as the limit is per browser and set to a very low number (6). The issue has been marked as "Won't fix" in Chrome and Firefox. This limit is per browser + domain, so that means that you can open 6 SSE connections across all of the tabs to www.example1.com and another 6 SSE connections to www.example2.com (thanks Phate).
  • Only WS can transmit both binary data and UTF-8, SSE is limited to UTF-8. (Thanks to Chado Nihi).
  • Some enterprise firewalls with packet inspection have trouble dealing with WebSockets (Sophos XG Firewall, WatchGuard, McAfee Web Gateway).

HTML5Rocks has some good information on SSE. From that page:

Server-Sent Events vs. WebSockets

Why would you choose Server-Sent Events over WebSockets? Good question.

One reason SSEs have been kept in the shadow is because later APIs like WebSockets provide a richer protocol to perform bi-directional, full-duplex communication. Having a two-way channel is more attractive for things like games, messaging apps, and for cases where you need near real-time updates in both directions. However, in some scenarios data doesn't need to be sent from the client. You simply need updates from some server action. A few examples would be friends' status updates, stock tickers, news feeds, or other automated data push mechanisms (e.g. updating a client-side Web SQL Database or IndexedDB object store). If you'll need to send data to a server, XMLHttpRequest is always a friend.

SSEs are sent over traditional HTTP. That means they do not require a special protocol or server implementation to get working. WebSockets on the other hand, require full-duplex connections and new Web Socket servers to handle the protocol. In addition, Server-Sent Events have a variety of features that WebSockets lack by design such as automatic reconnection, event IDs, and the ability to send arbitrary events.


TLDR summary:

Advantages of SSE over Websockets:

  • Transported over simple HTTP instead of a custom protocol
  • Can be poly-filled with javascript to "backport" SSE to browsers that do not support it yet.
  • Built in support for re-connection and event-id
  • Simpler protocol
  • No trouble with corporate firewalls doing packet inspection

Advantages of Websockets over SSE:

  • Real time, two directional communication.
  • Native support in more browsers

Ideal use cases of SSE:

  • Stock ticker streaming
  • twitter feed updating
  • Notifications to browser

SSE gotchas:

  • No binary support
  • Maximum open connections limit
残月升风 2024-10-27 11:28:41

据 caniuse.com 称:

您可以使用仅客户端的填充来将对 SSE 的支持扩展到许多其他浏览器。对于 WebSockets,这种情况不太可能发生。一些 EventSource polyfills:

如果您需要支持所有浏览器,请考虑使用类似 web-socket-jsSignalRsocket.io 支持多种传输,例如 WebSockets、SSE、Forever Frame 和 AJAX 长轮询。这些通常也需要对服​​务器端进行修改。

了解有关 SSE 的更多信息,请访问:

从以下位置了解有关 WebSocket 的更多信息:

其他区别:

  • WebSockets 支持任意二进制数据,SSE 仅使用 UTF-8

According to caniuse.com:

You can use a client-only polyfill to extend support of SSE to many other browsers. This is less likely with WebSockets. Some EventSource polyfills:

If you need to support all the browsers, consider using a library like web-socket-js, SignalR or socket.io which support multiple transports such as WebSockets, SSE, Forever Frame and AJAX long polling. These often require modifications to the server side as well.

Learn more about SSE from:

Learn more about WebSockets from:

Other differences:

  • WebSockets supports arbitrary binary data, SSE only uses UTF-8
余生再见 2024-10-27 11:28:41

到了2023年,情况已不再像以前那样了。

几年前,当 IE 仍然拥有重要的市场份额时,SSE 的一个缺点是总量IE 缺乏本机支持(而 IE 10+ 支持 WebSockets)。如今,根据caniuse.com,这两种技术在客户端几乎得到同样好的支持:WebSockets 为 98.35%SSE 为 98.03%< /a> (这些统计数据适用于全球用户)。

从历史上看,SSE 的一个严重限制,即每个域 6 个连接限制(在许多浏览器选项卡中打开 yourapp.com 时出现的问题)对于 HTTP/2。所有现代浏览器都支持 HTTP/297.16% 的全球用户)并在服务器上-side HTTP/2+ 在过去几年中也超越了 HTTP/1

在 SSE 和 WebSocket 之间进行选择时需要考虑各种因素:

  • SSE 通常更容易实现,并且更容易测试/调试(可以使用简单的 curl)。
  • WebSocket 支持双向(全双工)通信。也就是说,如果需要双向通信,SSE 可以与 AJAX 结合使用。在这些情况下,WebSocket 通常被认为是更简单的选择,但我认为这种概括可能会产生误导,因为它很大程度上取决于应用程序的类型、设计方式和使用的技术。
  • SSE 仅支持 UTF-8 文本消息,而 WebSocket 还可以传输二进制数据。
  • 我们可以在客户端通过内置的 EventSource API。然而,现在人们经常选择使用库,例如​​流行的 fetch-event-source,这是 EventSource 的 SSE 兼容替代方案,提供附加功能,例如自定义标头、更高级的重试策略、最小化浏览器时自动关闭连接等。
  • 从实际角度来看,我还建议研究如何那么您的应用程序服务器支持每一种技术。请注意,有些依赖于附加模块和/或库。您可能想查看一些示例,并可能构建一个快速的 PoC。

In 2023 the situation is not quite as it used to be.

Years ago, when IE still had a significant market share, one downside of SSE was the total lack of native support by IE (whereas WebSockets was supported by IE 10+). Nowadays, according to caniuse.com, both technologies are supported almost equally well on the client side: 98.35% for WebSockets vs 98.03% for SSE (those stats are for global users).

Historically, one severe limitation of SSE, the 6-connections-per-domain limit (a problem when yourapp.com is opened in many browser tabs) is not an issue anymore with HTTP/2. All modern browsers support HTTP/2 (97.16% of global users) and on the server-side HTTP/2+ has also surpassed HTTP/1 the last couple of years.

Various things need to be considered when chosing between SSE and WebSockets:

  • SSE is generally simpler to implement and easier to test/debug (a simple curl could be used).
  • WebSockets support bidirectional (full-duplex) communication. That said, SSE could be used in conjunction with AJAX if bidirectional communication is needed. WebSockets are often said to be the simpler option in those cases, but I think such generalizations can be misleading, as it largely depends on the type of application, how it's designed and the technologies used.
  • SSE supports UTF-8 text messages only, whereas WebSockets can also transmit binary data.
  • We can use SSE on the client side with the built-in EventSource API. However, nowadays people often choose to use a library, such as the popular fetch-event-source, which is an SSE-compatible alternative to EventSource that provides additional features, such as custom headers, more advanced retry strategies, automatically closing the connection when browser is minimized, etc.
  • From a practical standpoint, I'd also recommend to research how well your application server supports each of those technologies. Note that some rely on additional modules and/or libraries. You might want to look at some examples and maybe build a quick PoC.
狼性发作 2024-10-27 11:28:41

Websocket VS SSE


Web Sockets - 它是一种通过单个 TCP 连接提供全双工通信通道的协议。
例如服务器和浏览器之间的双向通信
由于协议比较复杂,服务器和浏览器都必须依赖websocket库
这是 socket.io

Example - Online chat application.

SSE(服务器发送事件)-
在服务器发送事件的情况下,通信仅从服务器到浏览器进行,浏览器不能向服务器发送任何数据。这种通讯方式主要用于
当只需要显示更新的数据时,服务器会在数据更新时发送消息。
例如服务器到浏览器之间的单向通信。
这种协议不太复杂,所以不需要依赖外部库JAVASCRIPT本身提供的EventSource接口来接收服务器发送的消息。

Example - Online stock quotes or cricket score website.

Websocket VS SSE


Web Sockets - It is a protocol which provides a full-duplex communication channel over a single TCP connection.
For instance a two-way communication between the Server and Browser
Since the protocol is more complicated, the server and the browser has to rely on library of websocket
which is socket.io

Example - Online chat application.

SSE(Server-Sent Event) -
In case of server sent event the communication is carried out from server to browser only and browser cannot send any data to the server. This kind of communication is mainly used
when the need is only to show the updated data, then the server sends the message whenever the data gets updated.
For instance a one-way communication between the Server to Browser.
This protocol is less complicated, so no need to rely on the external library JAVASCRIPT itself provides the EventSource interface to receive the server sent messages.

Example - Online stock quotes or cricket score website.
输什么也不输骨气 2024-10-27 11:28:41

Opera、Chrome、Safari 支持 SSE,
Chrome、Safari 在 SharedWorker 内部支持 SSE
Firefox 支持 XMLHttpRequest readState 交互,因此我们可以为 Firefox 制作 EventSource polyfil

Opera, Chrome, Safari supports SSE,
Chrome, Safari supports SSE inside of SharedWorker
Firefox supports XMLHttpRequest readyState interactive, so we can make EventSource polyfil for Firefox

讽刺将军 2024-10-27 11:28:41

需要注意的一件事:
我遇到了网络套接字和公司防火墙的问题。 (使用 HTTPS 有帮助,但并不总是如此。)

请参阅 https:// /github.com/LearnBoost/socket.io/wiki/Socket.IO-and-firewall-software
https://github.com/sockjs/sockjs-client/issues/94

假设服务器发送的事件没有那么多问题。但我不知道。

也就是说,WebSocket 非常有趣。我有一个使用 websockets 的小网页游戏(通过 Socket.IO)(http://minibman.com

One thing to note:
I have had issues with websockets and corporate firewalls. (Using HTTPS helps but not always.)

See https://github.com/LearnBoost/socket.io/wiki/Socket.IO-and-firewall-software
https://github.com/sockjs/sockjs-client/issues/94

I assume there aren't as many issues with Server-Sent Events. But I don't know.

That said, WebSockets are tons of fun. I have a little web game that uses websockets (via Socket.IO) (http://minibman.com)

深居我梦 2024-10-27 11:28:41

它们在语义上是不同的。

websocket 具有“双向数据流”的原生语义含义。

而 sse 具有“发布-订阅模式”或“请求-响应模式,尽管响应是流”的本机语义含义。

当然你可以自己在websocket上实现一层“pub-sub模式”或“req-res模式”。

they are different in semantics.

websocket has a native semantic meaning of "bidirectional data stream".

while sse has a native semantic meaning of "publish-subscribe pattern" or "request-respond pattern, despite the response is a stream".

of course you can implement a layer of "pub-sub pattern" or "req-res pattern" over websocket by yourself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文