Melody
Melody

Reputation: 127

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

I have to make a choice between WebSockets and SSE for an app that should send events in order to update a newsfeed on my website.

I kind of want to use SSE for this task since i don't have to allow users to send events to the server, i just want them to receive events.

Question is: are SSEs sending headers each time an event is sent from the server or just when the connection is created and the sends just the content of an event? If SSE send headers with each event should i use WebSockets to reduce bandwidth?

Upvotes: 3

Views: 1958

Answers (1)

Walter Monroe
Walter Monroe

Reputation: 320

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

Upvotes: 2

Related Questions