Question

Recently I've found out of Server-Sent events as a much simpler alternative to WebSockets for doing push from the server. Most places that compare them (like here, here and here) say that if you don't need full duplex communications between client and server, then WebSockets is overkill and SSE are good enough.

My question is what would be the downside of using SSE when you do need bidirectional communications (like a chat for example), using regular ajax requests for sending messages from the client and the server stream for receiving them? Considering that I have to do little to no configuration on the server side to use SSE, it seems to be a much more appealing option.

Was it helpful?

Solution

SSE Advantages over WebSockets:

  • No special web server or web proxy changes required.
  • Define custom events (otherwise, client API is basically the same)
  • Easier integration of existing authentication mechanisms (OAuth, OpenID, etc)

SSE Disadvantages compared to WebSockets:

  • Unidirectional communication channel (server to client). Client to server requires a separate channel.
  • Browser support is more limited (no native IE support whereas WebSockets is supported in IE 10): WebSockets, SSE
  • Relies on client to verify origin (possibly more vulnerable to XSS attacks than WebSockets)
  • No native support for binary types (WebSockets supports raw frames using ArrayBuffers and Blobs).
  • Requires a full fledged web server even if the SSE endpoint is not serving static web content (a standalone WebSocket server can be fairly simple)
  • SSE with AJAX for bi-directional communication will have MUCH higher round-trip latency and higher client->server bandwidth than using a WebSocket connection. This is due to the overhead of connection setup for every client->server AJAX request. Also, server->client latency can have spikes with SSE since in many configurations the long-held connection will eventually be closed (often every 30 seconds) and need to be re-opened causing a temporary spike in server->client latency as well.

References:

OTHER TIPS

Ajax requests are huge compared to small WebSocket messages. Standard HTTP requests (Ajax) include a lot of headers including cookies with every request while WebSocket messages is just a few bytes.

The good thing with HTTP (Ajax) request is that they are easier to cache if that is a benefit for your problem.

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