微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html5 – WebSockets VS服务器发送事件/ EventSource

WebSocketsServer-Sent Events都能将数据推送到浏览器。对我来说,他们似乎是竞争的技术。它们之间有什么区别?你什么时候选择一个

解决方法

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

Websockets连接可以将数据发送到浏览器并从浏览器接收数据。一个可以使用websockets的应用程序的好例子是聊天应用程序。

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

在实践中,因为可以使用WebSocket完成的一切都可以通过Websockets完成,Websockets得到了更多的关注和爱,并且许多浏览器支持Websockets比SSE。

然而,对于某些类型的应用程序,它可能是过度杀伤,并且后端可以更容易实现与协议,如SSE。

此外,SSE可以聚合到旧的浏览器,它不支持它本机只使用JavaScript。 SSE polyfills的一些实现可以在Modernizr github page上找到。

HTML5Rocks有一些关于上证的好信息。从该页:

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总结:

WebSocket上的SSE的优点:

>通过简单的HTTP而不是自定义协议传输
>可以多重填充javascript来“反向”SSE到不支持它的浏览器。
>内置支持重连接和事件id
>更简单的协议

WebSocket相对于SSE的优点:

>实时,双向通信。
>本地suport在更多的浏览器

SSE的理想用例:

>股票流通>推特更新>通知浏览器

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。