Websockets Vs. Server-Sent Events/Eventsource

WebSockets vs. Server-Sent events/EventSource

Websockets and SSE (Server Sent Events) are both capable of pushing data to browsers, however they are not competing technologies.

Websockets connections can both send data to the browser and receive data from the browser. A good example of an application that could use websockets is a chat application.

SSE connections can only push data to the browser. Online stock quotes, or twitters updating timeline or feed are good examples of an application that could benefit from SSE.

In practice since everything that can be done with SSE can also be done with Websockets, Websockets is getting a lot more attention and love, and many more browsers support Websockets than SSE.

However, it can be overkill for some types of application, and the backend could be easier to implement with a protocol such as SSE.

Furthermore SSE can be polyfilled into older browsers that do not support it natively using just JavaScript. Some implementations of SSE polyfills can be found on the Modernizr github page.

Gotchas:

  • SSE suffers from a limitation to the maximum number of open connections, which can be specially painful when opening various tabs as the limit is per browser and set to a very low number (6). The issue has been marked as "Won't fix" in Chrome and Firefox. This limit is per browser + domain, so that means that you can open 6 SSE connections across all of the tabs to www.example1.com and another 6 SSE connections to www.example2.com (thanks Phate).
  • Only WS can transmit both binary data and UTF-8, SSE is limited to UTF-8. (Thanks to Chado Nihi).
  • Some enterprise firewalls with packet inspection have trouble dealing with WebSockets (Sophos XG Firewall, WatchGuard, McAfee Web Gateway).

HTML5Rocks has some good information on SSE. From that page:

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 summary:

Advantages of SSE over Websockets:

  • Transported over simple HTTP instead of a custom protocol
  • Can be poly-filled with javascript to "backport" SSE to browsers that do not support it yet.
  • Built in support for re-connection and event-id
  • Simpler protocol
  • No trouble with corporate firewalls doing packet inspection

Advantages of Websockets over SSE:

  • Real time, two directional communication.
  • Native support in more browsers

Ideal use cases of SSE:

  • Stock ticker streaming
  • twitter feed updating
  • Notifications to browser

SSE gotchas:

  • No binary support
  • Maximum open connections limit

What is the difference between Websocket,Server Sent Events (SSE) and HTTP2's Server Pushing?

Websockets: asynchronous communication in both directions. So far doesn't work well with HTTP/2, but efforts are ongoing to make it so. (For example WISH and websockets2-over-http2.)

SSE: server can notify the browser of events. Uses normal HTTP and works well even with HTTP/2. It's possible to emulate asynchronous communication in both directions with SSE by issuing notifications from client to server via regular POST requests, in HTTP/2 these requests go in the same socket with everything else for the same origin and therefore the cost of establishing a new connection can be avoided. However, there may be processing costs on the server side for processing a POST request which are greater than using native websockets.

HTTP/2 Push: absolutely unrelated to the two above, it is a mechanism for a server to push assets to the browser in advance. Possible application: sending CSSs and Javascripts while the PHP engine is creating the HTML. In theory, HTTP/2 Push and SSE can be combined to make events available to the browser without the initial round-trip delay.

Server Sent Events and Ajax VS Websockets and Ajax

SSE, Web Sockets, and normal HTTP requests (via AJAX or Fetch API) are all different tools for different jobs.

SSE

  • Unidirectional, from server to client.
  • Text-based data only. (Anything else must be serialized, i.e. JSON.)
  • Simple API, widely compatible, auto-reconnects, has built-in provision for catching up on possibly missed events.

Web Sockets

  • Bi-directional.
  • Text or binary data.
  • Requires you to implement your own meaning for the data sent.

Standard HTTP Requests

  • Client to Server or Server to Client, but only one direction at a time.
  • Text or binary data.
  • Requires extra effort to stream server-to-client response in realtime.
  • Streaming from client-to-server requires that the entire data be known at the time of the request. (You can't do an event stream, for example.)

How to decide:

  • Are you streaming event-like data from the server to the client? Use SSE. It's purpose-built for this and is a dead simple way to go.
  • Are you sending data in only one direction, and you don't need to spontaneously notify clients of something? Use a normal HTTP request.
  • Do you need to send bidirectional data with a long-term established connection? Use Web Sockets.

From your description, it sounds like either SSE or Web Sockets would be appropriate for your use case. I'd probably lean towards SSE, while sending the random API calls from the client with normal HTTP requests.

I do not know what the solution would be because SSE seem like the better option as i do not need to continually handshake. If this handshake is truly inconsequential(which from everything i have read isn't the case) than WS is likely a better alternative.

Keep in mind that you can simply configure your server with HTTP keep-alive, making this point moot.

Why and how SSE (Server-Sent Events) are unidirectional

SSE is unidirectional because when you open a SSE connection, only the server can send data to the client (browser, etc.). The client cannot send any data. SSE is a bit older than WebSockets, hence may be the difference between the unidirectional and bi-directional support between these two technos.

In your use-case, if you open a SSE connection (which is an HTTP connection), only the server will be able to send data. If you wish to send a request to your HTTP service, you will need to open a new "classical" HTTP connection. You will see your browser opening two HTTP connections: 1 for the SSE connection and 1 for the classical HTTP request (short live).

You can implement a chat with SSE. You can have a SSE connection (hence HTTP) to let the user receives the messages from the server. And you can use POST HTTP requests to enable the user to send his/her messages.

Note that most of the browsers can open around 6 HTTP/1.x connections to the same host. So, if you use 1 SSE connection, it will remain potentially 5 HTTP/1.x connections. This is only true with HTTP/1.x. With HTTP 2.x, the connections to the same host are multiplexed: so, in theory, you can send as many HTTP requests at the same time as you wish or you can open as many SSE connections as you wish and thus, by passing the limitation of the 6 connections.

You can have a look at this article (https://streamdata.io/blog/push-sse-vs-websockets/) and this video (https://www.youtube.com/watch?v=NDDp7BiSad4) to get an insight about this technology and whether it could fit your needs. They summarize pros & cons of both SSE and WebSockets.

Server sent event vs web sockets?

Some things to keep in mind when making this choice.

  • Attempting to fetch content over a WebSocket connection is a poor
    design decision because WebSockets is a different protocol nested
    inside an HTTP connection and it can't leverage caching (neither the
    browsers nor CDNs).
  • Some older proxies won't pass on a Websocket connection unless its hidden within a secure connection while Server
    Sent Events remains an HTTP connection and won't suffer from
    this.
  • Neither WebSockets nor SSE are supported in the native Android
    browser until 4.4 (when they switched to using Chrome) - thus if
    you're considering a hybrid mobile app, you will need a fallback such
    as SocketIO since, as of this writing, 4.4 is only 20% of the market
    and hybrid apps use the native Android browser.
  • WebSockets is the
    most battery efficient protocol for mobile devices, since all other
    options require many HTTP connections and it is the repeated
    negotiating of the headers that will burden the cpu and drain the
    battery.

Another option may be notifications. All mobile devices now support notifications that can be targeted to an App and a number of browsers have as well. In all cases a connection already exists from the client to the messaging center (Apple, Google, Microsoft, etc) and all notifications are sent over this channel.

Here's a good overview of WebSockets vs. SSE:
http://www.html5rocks.com/en/tutorials/eventsource/basics/

Are Server-Sent Events sending headers each time an event is sent from the server or just when the connection is created?

With SSE, headers are sent only when the connection is created. After that you simply send event data to each open connection as needed.

For one-way traffic, SSE generally uses less server resources than WebSockets and runs over normal http/https protocol for lower risk of firewall/gateway issues. Even group chat can be implemented with a combination of SSE and AJAX.

Some example Node.js code:

const connections = [];

function connect(req, res) {
connections.push(res);
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache',
'X-Accel-Buffering': 'no'
});
req.on('close', () => {
connections.splice(connections.indexOf(res), 1);
});
}

function send(data) {
connections.forEach(c => c.write(`data:${JSON.stringify(data)}\n\n`));
}

Server-Sent Events official specs:
https://html.spec.whatwg.org/multipage/server-sent-events.html
https://www.w3.org/TR/eventsource/

Marmelab has one was the most useful tutorials because it shows how to configure routes for multiple chat rooms:
https://marmelab.com/blog/2020/10/02/build-a-chat-application-using-sveltejs-and-sse.html

Here's a superb demonstration of how response objects can be stored in array with no other identifiers
and deleted when the connection is closed. Wow! How the heck does Node.js compare responses? #hashcodes?
https://cri.dev/posts/2021-05-11-simple-server-sent-events-sse-eventsource-nodejs-javascript

One of many good tutorials from DigitalOcean community:
https://www.digitalocean.com/community/tutorials/nodejs-server-sent-events-build-realtime-app

A very popular reference with a note re: Cross-document messaging security via EventSource.origin:
https://www.html5rocks.com/en/tutorials/eventsource/basics/

Watch out for compression middleware:
https://jasonbutz.info/2018/08/server-sent-events-with-node

HTML5 Server-Side Event: EventSource vs. wrapped WebSocket

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.

Server Side Events + Client Side Events vs Websocket

This is the best explanation for SSE and its flexibilty

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.

I had built a chat application using sse and ajax for my site.I would suggest sse + ajax would be way to go if there is only stream updates and very few updates from client to server for that you can use the ajax part

Only problem that I found is its lack of support across browsers .And if you want to know more in depth about sse ask specifically what you want

Browser Support List



Related Topics



Leave a reply



Submit