前端实现实时数据更新:EventSource

前言

大看板相信很多人都做过,通常就是用来展示数据的。最初一些同事(包括我自己)都是通过定时器来实现的,每隔多长时间发送一次请求。后来用户说页面不刷新或者是页面卡死了,讨论的解决方案是改成WebSocket实时推送消息。最近看到一篇文章是介绍EventSource的,EventSourceWebSocket更适合用来更新数据

通过询问gpt,定时器、WebSocket还是EventSource哪一个用来实时更新数据后更加让我想要了解一下EventSource

在这里插入图片描述
关于WebSocketEventSource的介绍,大家可以看官方文档:

Web API接口:EventSource

Web API接口:WebSocket

简单示例

服务器端
这一部分使用node写的,a.js

const http = require("http");

http
  .createServer((req, res) => {
    
    
    // 处理跨域
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type");
    // 设置请求头
    res.writeHead(200, {
    
    
      "Content-Type": "text/event-stream;charset=utf-8;",
      "Cache-Control": "no-cache",
      Connection: "keep-alive",
    });

    console.log("服务已启动:http://localhost:3000/");

    let counter = Math.floor(Math.random() * 10) + 1;

    const sendPing = () => {
    
    
      const curDate = new Date().toLocaleString();
      res.write(`event: ping\ndata: {
    
    "time": "${
      
      curDate}"}\n\n`);
    };

    const sendMessage = () => {
    
    
      const curDate = new Date().toLocaleString();
      res.write(`data: 这是一条消息,在${
    
    curDate}\n\n`);
      counter = Math.floor(Math.random() * 10) + 1;
    };

    const intervalId = setInterval(() => {
    
    
      sendPing();
      counter--;

      if (counter === 0) {
    
    
        sendMessage();
      }
    }, 1000);

    req.on("close", () => {
    
    
      clearInterval(intervalId);
      res.end();
    });
  })
  .listen(3000);

启动方式也很简单,在该文件所在的文件夹下打开终端,输入node node .\a.js,服务就启动了

前端
b.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Server-sent events demo</title>
  </head>
  <body>
    <button>关闭连接</button>

    <ul></ul>

    <script>
      const button = document.querySelector("button");
      // 设置连接地址
      const evtSource = new EventSource("http://localhost:3000/");
      // 一个布尔值,表示 EventSource 对象是否使用跨源资源共享(CORS)凭据来实例化(true),或者不使用(false,即默认值)。
      console.log("withCredentials:", evtSource.withCredentials);
      //一个代表连接状态的数字。可能值是 CONNECTING(0)、OPEN(1)或 CLOSED(2)。
      console.log("readyState:", evtSource.readyState);
      //   一个表示事件源的 URL 字符串。
      console.log("url:", evtSource.url);
      const eventList = document.querySelector("ul");

      evtSource.onopen = function () {
    
    
        console.log("服务连接成功.");
      };

      // 接受消息
      evtSource.onmessage = function (e) {
    
    
        const newElement = document.createElement("li");

        newElement.textContent = "message: " + e.data;
        eventList.appendChild(newElement);
      };

      // 错误处理
      evtSource.onerror = function () {
    
    
        console.log("EventSource failed.");
      };

      button.onclick = function () {
    
    
        console.log("连接已关闭");
        evtSource.close();
      };

      // 监听某一个具体的事件发送的消息
      evtSource.addEventListener(
        "ping",
        function (e) {
    
    
          var newElement = document.createElement("li");

          var obj = JSON.parse(e.data);
          newElement.innerHTML = "ping at " + obj.time;
          eventList.appendChild(newElement);
        },
        false
      );
    </script>
  </body>
</html>

效果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41897680/article/details/131372847
今日推荐