Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top