Node.js SSE in Action All In One

发布时间 2023-10-23 09:45:59作者: xgqfrms

Node.js SSE in Action All In One

Node.js & Server-sent events

SSE

Server-sent events: method of continuously sending data from a server to the browser, rather than repeatedly requesting it (EventSource interface, used to fall under HTML5)

image

https://caniuse.com/eventsource

var source = new EventSource('updates.cgi');
source.onmessage = function (event) {
  alert(event.data);
};
var source = new EventSource('updates.cgi');
source.addEventListener('add', addHandler, false);
source.addEventListener('remove', removeHandler, false);

https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events

https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events

EventSource

⚠️ Warning: When not used over HTTP/2, 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.
When using HTTP/2, the maximum number of simultaneous HTTP streams is negotiated between the server and the client (defaults to 100).

const evtSource = new EventSource("sse.php");
const eventList = document.querySelector("ul");

evtSource.onmessage = (e) => {
  const newElement = document.createElement("li");
  newElement.textContent = `message: ${e.data}`;
  eventList.appendChild(newElement);
};


https://developer.mozilla.org/en-US/docs/Web/API/EventSource

demos

server.js


client.js


(? 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://stackoverflow.com/questions/77341435/nodejs-sending-image-files-using-sse

https://stackoverflow.com/questions/5195452/websockets-vs-server-sent-events-eventsource/5326159



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 ?️,侵权必究⚠️!