EventSource

javascript

if ('EventSource' in window) {
  const source = new EventSource('http://127.0.0.1:8080/stream');
  const { readyState } = source;

  source.onopen = function (event) {
    console.log('event', event);
  };

  source.onmessage = function (event) {
    const { data } = event;
    console.log('data', data);
  };

  source.onerror = function (error) {
    console.log('error', error);
  };

  // source.close();
}

node

const http = require('http);

http.createServe(function (req, res) {
  const fileName = '.' + req.url;

  if (fileName === './stream') {
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Access-Control-Allow-Origin': '*',
    });
    res.write('retry: 10000\n');
    res.write('event: connectTime\n');
    res.write('data: ' + (new Date()) + '\n\n');

    const interval = setInterval(function() {
      res.write('data: ' + (new Date()) + '\n\n');
    }, 1000 * 100);

    req.addListener('close', function() {
      clearInterval(interval);
    }, false);
  }
}).listen(8080, '127.0.0.1');

文档

MDN: https://developer.mozilla.org/zh-CN/docs/Web/API/EventSourceopen in new window

SSE: http://www.ruanyifeng.com/blog/2017/05/server-sent_events.htmlopen in new window