发布时间:2023-06-01 文章分类:WEB开发, 电脑百科 投稿人:赵颖 字号: 默认 | | 超大 打印

SSE 与 WebSocket 作用相似,都是建立浏览器与服务器之间的通信渠道,然后服务器向浏览器推送信息SSE 是单向通道,只能服务器向浏览器发送,因为流信息本质上就是下载。如果浏览器向服务器发送信息,就变成了另一次 HTTP 请求

使用方法 

Server-Sent Events 教程 - 阮一峰的网络日志Server-Sent Events(以下简称 SSE)及event-source-polyfill使用单向长连接(后台主动向前端推送)https://www.ruanyifeng.com/blog/2017/05/server-sent_events.html

缺点:不可以比如请求头中加token等

 getSSE() {
      return new Promise((resolve, reject) => {
        let base = process.env.VUE_APP_SYSTEMURL;
        let url = `${base}/server/sampleRemovePush/sse`;
        if (window.EventSource) {
          this.SSE = new EventSource(url);
          this.SSE.addEventListener(
            "open",
            e => {
              console.log("建立连接。。。", e);
            },
            false
          );
          this.SSE.addEventListener(
            "message",
            event => {
              console.log("ebent", event);
              resolve(event);
            },
            false
          );
          this.SSE.addEventListener(
            "error",
            event => {
              // readyState连接状态: 0 - connecting; 1 - open; 2 - closed;
              if ((event.readyState = EventSource.CLOSED)) {
                console.log("sse错误------", event);
                reject("请求错误!");
              } else {
                resolve(event);
              }
            },
            false
          );
          // this.SSE.addEventListener("close", event => {
          //   console.log("我要关闭啦", event.type);
          //   this.SSE.close();
          // });
        } else {
          console.log("你的浏览器不支持SSE");
        }
      });
    },

 如果加自定义参数可以使用三方插件event-source-polyfill

GitHub - Yaffle/EventSource: a polyfill for http://www.w3.org/TR/eventsource/a polyfill for http://www.w3.org/TR/eventsource/. Contribute to Yaffle/EventSource development by creating an account on GitHub.Server-Sent Events(以下简称 SSE)及event-source-polyfill使用单向长连接(后台主动向前端推送)https://github.com/Yaffle/EventSource/使用方法

npm install event-source-polyfill

import {EventSourcePolyfill} from 'event-source-polyfill';
  let base = process.env.VUE_APP_SYSTEMURL;
      let url = `${base}/server/sampleRemovePush/sse`;
      let { access_token } = this.$store.state.login.login;
      var es = new EventSourcePolyfill(url, {
        headers: {
          Authorization: access_token ? `Bearer${access_token}` : ""
        }
      });
      es.onopen = function(event) {
        console.log("连接成功", event);
      };
      es.onmessage = function(event) {
        // to to something…
        console.log("接收信息", event);
      };
      es.onerror = function(error) {
        // 监听错误
        console.log("错误", error);
      };

可 以看到token是有加上去的 

Server-Sent Events(以下简称 SSE)及event-source-polyfill使用单向长连接(后台主动向前端推送)