Server-Sent 事件是在每次从服务器发送事件时发送 headers 事件还是仅在创建连接时发送?

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

我必须在 WebSockets 和 SSE 之间做出选择,因为应用程序应该发送事件以更新我网站上的新闻源。

我有点想使用 SSE 来完成这项任务,因为我不需要允许用户向服务器发送事件,我只希望他们接收事件。

问题是:SSE 是在每次从服务器发送事件时发送 headers 还是仅在创建连接并且仅发送事件内容时发送?如果 SSE 在每个事件中发送 headers,我应该使用 WebSockets 来减少带宽吗?

使用 SSE,headers 仅在创建连接时发送。之后,您只需根据需要向每个打开的连接发送事件数据。

对于 one-way 流量,SSE 通常使用比 WebSockets 更少的服务器资源,并在正常 http/https 协议上运行,以降低 firewall/gateway 问题的风险。甚至群聊也可以通过SSE和AJAX.

的组合来实现

一些例子Node.js代码:

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 活动官方规格: https://html.spec.whatwg.org/multipage/server-sent-events.html https://www.w3.org/TR/eventsource/

Marmelab 有一个最有用的教程,因为它展示了如何为多个聊天室配置路由: https://marmelab.com/blog/2020/10/02/build-a-chat-application-using-sveltejs-and-sse.html

这是一个关于如何将响应 objects 存储在没有其他标识符的数组中的精彩演示 并在连接关闭时删除。哇! Node.js 到底是如何比较响应的? #哈希码? https://cri.dev/posts/2021-05-11-simple-server-sent-events-sse-eventsource-nodejs-javascript

来自 DigitalOcean 社区的众多优秀教程之一: https://www.digitalocean.com/community/tutorials/nodejs-server-sent-events-build-realtime-app

一个非常受欢迎的参考,附注:Cross-document 通过 EventSource.origin 的消息传递安全性: https://www.html5rocks.com/en/tutorials/eventsource/basics/

注意压缩中间件: https://jasonbutz.info/2018/08/server-sent-events-with-node