问题
Is the HTML5 Server-Sent Events (SSE) API just a restricted, event-based API on top of HTML5 WebSockets?
It seems to me that an EventSource
is just a WebSocket
that:
- Cannot
.send()
data - Uses the
text/event-stream
format - Fires dynamically-named (server-defined) events instead of
onmessage
The idea of the web server pushing events down to client devices is quite intriguing. Does this API have any traction?
I imagine the async event model would work beautiful when couple with Node, but not seeing a lot of use cases for this in my ASP.NET world.
回答1:
Server Sent Events is useful in applications that only needs server push while Web Sockets are good for applications that needs fast communications in both directions.
Examples where Server Sent Events are a good solution are:
- Stock Value changes
- News feeds
Server Sent Events do some more things that is not built-in in Web Sockets, such as automatic reconnection and eventIDs.
Server Sent events also has broader web browser support as of today, with support in Safari (only support older drafts of Web Sockets) and Opera (has Web Sockets disabled by default, and uses an older draft).
Read more about Server Sent Events on Stream Updates with Server-Sent Events.
回答2:
In addition to what Jonas said, the protocols are entirely different.
The WebSocket Protocol
(RFC 6455) starts as an HTTP connection, then uses a handshake to upgrade the connection to the new protocol. This is a binary protocol that uses framing, message types, and more.Server-Sent Events
is a long running HTTP request that stays open. The server sends messages in a simple text-based format (UTF-8
encoding), delimited by\n\n
. A message has fieldsevent
(the event type),data
,id
, and can optionally include comments.
One major difference is the security model. With WebSockets, the default is to let anyone connect. Rejecting a connection must be done on the server side, based on the Origin
header.
SSE on the other hand, is closer to HTTP and uses same-origin policy. By default you can only make requests to the same host and port. In the future it will be possible to use CORS to make cross-domain SSE requests. As of today, browsers have not implemented this yet.
The two protocols take different approaches, as they solve different problems.
来源:https://stackoverflow.com/questions/8499142/html5-server-side-event-eventsource-vs-wrapped-websocket