使用服务器端事件向浏览器动态发送消息

Use server side events to dynamically send message to browser

我希望使用 SSE 向浏览器动态发送消息。理想情况下,我想要一个最小的应用程序,其中浏览器在调用函数或方法(将消息作为参数)之前不执行任何操作并且浏览器收到此消息并仅记录一次。我试图用以下内容来说明这一点:

const http = require("http");
const server = http.createServer(<not sure what code goes here>);
server.listen(8000);

// this can be called at any time after creating the server so the browser 
// can receive the message and log it to the console.
sendMessageToBrowser(`data: this is a dynamic message\n\n`) 

但是,下面的基本 SSE 应用程序只是每 3 秒(默认)将 "hello world" 记录到浏览器控制台。我不明白这与通过常规路由和使用类似以下内容提供数据有何不同:

setInterval(fetch("/events").then(res => res.text()).then(data => console.log(data)));

我的请求是否可以通过 SSE 实现,还是我误解了它的工作原理?我知道我的请求可以通过 websockets/socket.io 实现,但我希望使用 SSE,因为我不想使用更易于理解和实施的库和 SSE。

每 3 秒记录一次 hello world 的最小示例:

const http = require("http");

const server = http.createServer((req, res) => {
  // Server-sent events endpoint
  if (req.url === "/events") {
    res.writeHead(200, {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
      Connection: "keep-alive",
    });
    res.end(`data: hello world\n\n`);
    return;
  }

  // Client side logs message data to console
  res.writeHead(200, { "Content-Type": "text/html" });
  res.end(`
      <script>
        var eventSource = new EventSource('/events');
        eventSource.onmessage = function(event) {
          console.log(event.data);
        };
      </script>
  `);
});

server.listen(8000);

不知道我是否真的理解你的需求。我更改了代码,现在如果您转到 /sendEvent url,您会在根页面中看到一个新日志。 您可以在任何函数中使用 resEvents var 在根页面中记录新消息。

const http = require("http");
var resEvents;
var count = 0;

var myInterval = setInterval(() => {
  if (count < 50) sendMessageToBrowser(count);
  else clearInterval(myInterval);
}, 1000);

function sendMessageToBrowser(msg) {
  if (resEvents) {
    resEvents.write(`data: ${msg}\n\n`);
    count++;
  }
}

const server = http.createServer((req, res) => {
  // Server-sent events endpoint
  if (req.url === "/events") {
    resEvents = res;
    res.writeHead(200, {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
      Connection: "keep-alive"
    });
    res.write(
      `data: Go to http://localhost:8000/sendEvent to log a new Messages \n\n`
    );
    return;
  }

  if (req.url === "/sendEvent") {
    if (!resEvents) {
      res.writeHead(200, { "Content-Type": "text/html" });
      res.end(`Logged a new Message<br>Refresh the page to log a new Message`);
      resEvents.write(
        `data: From Url: ${Math.floor(Math.random() * 5000) + 1}\n\n`
      );
    } else {
      res.writeHead(200, { "Content-Type": "text/html" });
      res.end(`First go to http://localhost:8000/`);
    }
    return;
  }

  // Client side logs message data to console
  res.writeHead(200, { "Content-Type": "text/html" });
  res.end(`
      <script>
        var eventSource = new EventSource('/events');
        eventSource.onmessage = function(event) {
          console.log(event.data);
        };
      </script>
  `);
});

server.listen(8000);

更新

我添加了sendMessageToBrowser功能。它位于 setInterval 中,因此您可以看到服务器每秒向浏览器发送最多 50 条消息。

这是@Mattia 回答的精简版。

const http = require("http");
var resEvents;

const server = http.createServer((req, res) => {
  if (req.url === "/events") {
    resEvents = res;
    res.writeHead(200, {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
      Connection: "keep-alive",
    });
    return;
  }

  res.writeHead(200, { "Content-Type": "text/html" });
  res.end(`
      <script>
        var eventSource = new EventSource('/events');
        eventSource.onmessage = function(event) {
          console.log(event.data);
        };
      </script>
  `);
});

server.listen(8000);

// this can only be run after the browser has connected - either run code
// sequentially in a REPL or put this in a setTimeout() to give you time 
// to go to localhost:8000
resEvents.write(`data: hello\n\n`);