【SSE】前端vue3使用SSE,EventSource携带哀求头

打印 上一主题 下一主题

主题 1031|帖子 1031|积分 3093

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
一、SSE介绍

1. 界说

SSE(Server-Sent Events)是一种基于 HTTP 协议,用于实现服务器主动向客户端推送数据的技能。它在客户端与服务器之间创建一条持久化连接,并通过这条连接实现服务器向客户端的实时数据推送,而客户端不能发送数据给服务端。
总之——SSE是一种答应服务器向客户端单向发送数据的技能。

2. 特点



  • 单向通讯
  • 实时推送
  • 轻量级
  • 支持跨域、使用简朴、支持主动重连

3. 得当场景



  • 数据大屏
  • 消息推送
  • 股票交易
  • 在线聊天
  • ...

二、SSE使用

1. 创建最基本的SSE连接,需要用到  EventSource

<blockquote class="default_cursor_land">  EventSource接口是Web内容与服务器发送事件通讯的接口。
  一个EventSource实例向HTTP服务器开启一个持久化的连接,以text/event-stream格式发送事件,此连接会不停保持开启直到通过调用EventSource.close()关闭。
  示例:在一个vue的页面中
  1. const initSSE = () => {
  2.     eventSource = new EventSource('http://地址');
  3.     eventSource.onmessage = (event) => {
  4.         console.log("收到消息内容是:", event.data)
  5.     };
  6.     eventSource.onerror = (error) => {
  7.         console.error("SSE 连接出错:", error);
  8.         eventSource.close();
  9.     };
  10. }
  11. onMounted(() => {
  12.     initSSE();
  13. });
  14. onUnmounted(() => {
  15.     if (eventSource) {
  16.         eventSource.close();
  17.     }
  18. });
复制代码

2. EventSource的事件

open在与事件源的连接打开时触发
message在从事件源接收到数据时触发
error在事件源连接未能打开时触发
具名事件 当从服务器端接收到指定了event字段的事件时触发,这将创建一个以该键值为值的特定事件

3. 创建SSE连接的时候携带token

假如想要在创建SSE连接的时候携带token,需要用到 event-source-polyfill
<blockquote class="default_cursor_land">  EventSourcePolyfill 是 EventSource 封装好了的一个方法,可以直接设置哀求头
  起首安装依靠
  1. npm install event-source-polyfill --save
复制代码
项目中使用,完整的封装代码如下  sse.js 文件
  1. import {getToken} from "@/utils/auth";
  2. import {EventSourcePolyfill} from "event-source-polyfill";
  3. let eventSource = null;
  4. let reconnectAttempts = 0; // 重连次数
  5. export default function subscribeWarnMsg(proxy, url) {
  6.     if (eventSource) {
  7.         console.log("sse已经存在:", eventSource);
  8.         return eventSource;
  9.     } else {
  10.         eventSource = new EventSourcePolyfill(import.meta.env.VITE_APP_BASE_API + url, {
  11.             heartbeatTimeout: 3 * 60 * 1000,
  12.             headers: {
  13.                 Authorization: 'Bearer ' + getToken(),
  14.                 Accept: 'text/event-stream'
  15.             },
  16.             withCredentials: true,
  17.         })
  18.         eventSource.onopen = function (e) {
  19.             console.log(e, "连接刚打开时触发");
  20.             reconnectAttempts = 0; // 重置重连次数
  21.         };
  22.         eventSource.onmessage = (event) => {
  23.             console.log("收到消息内容是:", event.data)
  24.         };
  25.         eventSource.onerror = (event) => {
  26.             console.error("SSE 连接出错:", event);
  27.             eventSource.close(); // 关闭连接
  28.             eventSource = null;
  29.             // 自动重连逻辑
  30.             reconnectAttempts++;
  31.             const reconnectDelay = Math.min(30000, 1000 * Math.pow(2, reconnectAttempts)); // 计算重连延迟,最大延迟为30秒
  32.             console.log(`将在 ${reconnectDelay} 毫秒后尝试重连...`);
  33.             // 等待一定时间后重连
  34.             setTimeout(() => {
  35.                 if (!eventSource) {
  36.                     console.log("尝试重连 SSE...");
  37.                     subscribeWarnMsg(proxy, url); // 递归调用重连
  38.                 }
  39.             }, reconnectDelay);
  40.         }
  41.         return eventSource;
  42.     }
  43. }
复制代码
页面中使用  test.vue 文件
  1. import subscribeWarnMsg from '@/../sse'
  2. const {proxy} = getCurrentInstance();
  3. const sse = ref()
  4. function initSSE() {
  5.   sse.value = subscribeWarnMsg(proxy, `/system/sse/connect`);
  6.   sse.value.onmessage = async (event) => {
  7.     info.value = await JSON.parse(event.data)
  8.   }
  9. }
  10. onMounted(() => {
  11.   initSSE();
  12. });
  13. onUnmounted(() => {
  14.   sse.value.close()
  15. });
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

道家人

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表