EventSource

AI 打印机效果

HTTP协议中服务端的推送

服务端

const http = require('http');

// 将歌词变成一个数组
let song = [
  '', '', '', '', '', '', '', '', '', '', '', '', '', 
  '', '', '', '', '', '', '', '', '', '', '', '', '', 
  '', '', '', '', '', '', '', '', '', '', '', '', '', 
  '', '', '', '', '', '', '', '', '', '', '', '', '', 
  '', '', '', '', '', '', '', '', '', '', '', '', '', 
  '', '', '', '', '', '', '', '', '', '', '', '', '', 
  '', '', '', '', '', '', '', '', '', '', '', '', '', 
  '', '', '', '', '', '', '', '', '', '', '', '', '', 
  '', '', '', '', '', '', '', '', '', '', '', '', 'end'
];

http.createServer((req, res) => {

  if (req.url === '/article') {
    res.writeHead(200, {
      // 开启 Server-sent events
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      // 保持连接
      'Connection': 'keep-alive',
      // 允许跨域
      'Access-Control-Allow-Origin': '*'
    });
    let index = 0;

    // 模拟每隔0.5s向前端推送一次
    setInterval(() => {
      const s = song[index];

      if (s) {
        res.write(`data: ${song[index]}\n\n`);
      } else {
        res.write('0');
      }
      index++;
    }, 500);
  }
}).listen(3000);

console.log('Server running at http://localhost:3000/');

关键点'Content-Type': 'text/event-stream'

客户端

关键点:使用EventSourceAPI发起请求,并通过监听事件做相应操作

参考:

Last updated