HTML5 Server-Side Event: EventSource vs. wrapped WebSocket

旧时模样 提交于 2020-01-01 06:54:20

问题


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:

  1. Cannot .send() data
  2. Uses the text/event-stream format
  3. 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 fields event (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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!