Muizz Mahdy
Muizz Mahdy

Reputation: 808

Bidirectional client-server communication using Server-Sent Events instead of WebSockets?

It is possible to achieve two-way communication between a client and server using Server Sent Events (SSE) if the clients send messages using HTTP POST and receive messages asynchronously using SSE.

It has been mentioned here that SSE with AJAX would have higher round-trip latency and higher client->server bandwidth since an HTTP request includes headers and that websockets are better in this case, however isn't it advantageous for SSE that they can be used for consistent data compression, since websockets' permessage-deflate supports selective compression, meaning some messages might be compressed while others aren't compressed

Upvotes: 2

Views: 1873

Answers (2)

Fabian Andrei
Fabian Andrei

Reputation: 50

Your best bet in this scenario would be to use a WebSockets server because building a WS implementation from scratch is not only time-consuming but the fact that it has already been solved makes it useless. As you've tagged Socket.io, that's a good option to get started. It's an open source tool and easy to use and follow from the documentation.

However, since it is open-source, it doesn't provide some functionality that is critical when you want to stream data in a production level application. There are issues like scalability, interoperability (for endpoints operating on protocols other than WebSockets), fault tolerance, ensuring reliable message ordering, etc.

The real-time messaging infrastructure plus these critical production level features mentioned above are provided as a service called a 'Data Stream Network'. There are a couple of companies providing this, such as Ably, PubNub, etc.

I've extensively worked with Ably so comfortable to share an example in Node.js that uses Ably:

var Ably = require('ably');
var realtime = new Ably.Realtime('YOUR-API-KEY');
var channel = realtime.channels.get('data-stream-a');
  //subscribe on devices or database
  channel.subscribe(function(message) {
  console.log("Received: "  message.data);
});

//publish from Server A
channel.publish("example", "message data");

You can create a free account to get an API key with 3m free messages per month, should be enough for trying it out properly afaik.

There's also a concept of Reactor functions, which is essentially invoking serverless functions in realtime on AWS, Azure, Gcloud, etc. You can place a database on one side too and log data as it arrives. Pasting this image found on Ably's website for context:

enter image description here

Hope this helps!

Upvotes: 1

Evert
Evert

Reputation: 99851

Yes, it's possible.

You can have more than 1 parallel HTTP connection open, so there's nothing stopping you.

Upvotes: 2

Related Questions