前端vue3使用SSE、EventSource攜帶請(qǐng)求頭實(shí)例代碼
一、SSE介紹
1. 定義
SSE(Server-Sent Events)是一種基于 HTTP 協(xié)議,用于實(shí)現(xiàn)服務(wù)器主動(dòng)向客戶端推送數(shù)據(jù)的技術(shù)。它在客戶端與服務(wù)器之間建立一條持久化連接,并通過(guò)這條連接實(shí)現(xiàn)服務(wù)器向客戶端的實(shí)時(shí)數(shù)據(jù)推送,而客戶端不能發(fā)送數(shù)據(jù)給服務(wù)端。
總之——SSE是一種允許服務(wù)器向客戶端單向發(fā)送數(shù)據(jù)的技術(shù)。
2. 特點(diǎn)
- 單向通信
- 實(shí)時(shí)推送
- 輕量級(jí)
- 支持跨域、使用簡(jiǎn)單、支持自動(dòng)重連
3. 適合場(chǎng)景
- 數(shù)據(jù)大屏
- 消息推送
- 股票交易
- 在線聊天
- ...
二、SSE使用
1. 建立最基本的SSE連接,需要用到 EventSource
EventSource接口是Web內(nèi)容與服務(wù)器發(fā)送事件通信的接口。一個(gè)
EventSource實(shí)例向HTTP服務(wù)器開(kāi)啟一個(gè)持久化的連接,以text/event-stream格式發(fā)送事件,此連接會(huì)一直保持開(kāi)啟直到通過(guò)調(diào)用EventSource.close()關(guān)閉。
示例:在一個(gè)vue的頁(yè)面中
const initSSE = () => {
eventSource = new EventSource('http://地址');
eventSource.onmessage = (event) => {
console.log("收到消息內(nèi)容是:", event.data)
};
eventSource.onerror = (error) => {
console.error("SSE 連接出錯(cuò):", error);
eventSource.close();
};
}
onMounted(() => {
initSSE();
});
onUnmounted(() => {
if (eventSource) {
eventSource.close();
}
});2. EventSource的事件
| open | 在與事件源的連接打開(kāi)時(shí)觸發(fā) |
| message | 在從事件源接收到數(shù)據(jù)時(shí)觸發(fā) |
| error | 在事件源連接未能打開(kāi)時(shí)觸發(fā) |
| 具名事件 | 當(dāng)從服務(wù)器端接收到指定了event字段的事件時(shí)觸發(fā),這將創(chuàng)建一個(gè)以該鍵值為值的特定事件 |
3. 建立SSE連接的時(shí)候攜帶token
如果想要在建立SSE連接的時(shí)候攜帶token,需要用到 event-source-polyfill
EventSourcePolyfill 是 EventSource 封裝好了的一個(gè)方法,可以直接配置請(qǐng)求頭
首先安裝依賴
npm install event-source-polyfill --save
項(xiàng)目中使用,完整的封裝代碼如下 sse.js 文件
import {getToken} from "@/utils/auth";
import {EventSourcePolyfill} from "event-source-polyfill";
let eventSource = null;
let reconnectAttempts = 0; // 重連次數(shù)
export default function subscribeWarnMsg(proxy, url) {
if (eventSource) {
console.log("sse已經(jīng)存在:", eventSource);
return eventSource;
} else {
eventSource = new EventSourcePolyfill(import.meta.env.VITE_APP_BASE_API + url, {
heartbeatTimeout: 3 * 60 * 1000,
headers: {
Authorization: 'Bearer ' + getToken(),
Accept: 'text/event-stream'
},
withCredentials: true,
})
eventSource.onopen = function (e) {
console.log(e, "連接剛打開(kāi)時(shí)觸發(fā)");
reconnectAttempts = 0; // 重置重連次數(shù)
};
eventSource.onmessage = (event) => {
console.log("收到消息內(nèi)容是:", event.data)
};
eventSource.onerror = (event) => {
console.error("SSE 連接出錯(cuò):", event);
eventSource.close(); // 關(guān)閉連接
eventSource = null;
// 自動(dòng)重連邏輯
reconnectAttempts++;
const reconnectDelay = Math.min(30000, 1000 * Math.pow(2, reconnectAttempts)); // 計(jì)算重連延遲,最大延遲為30秒
console.log(`將在 ${reconnectDelay} 毫秒后嘗試重連...`);
// 等待一定時(shí)間后重連
setTimeout(() => {
if (!eventSource) {
console.log("嘗試重連 SSE...");
subscribeWarnMsg(proxy, url); // 遞歸調(diào)用重連
}
}, reconnectDelay);
}
return eventSource;
}
}頁(yè)面中使用 test.vue 文件
import subscribeWarnMsg from '@/../sse'
const {proxy} = getCurrentInstance();
const sse = ref()
function initSSE() {
sse.value = subscribeWarnMsg(proxy, `/system/sse/connect`);
sse.value.onmessage = async (event) => {
info.value = await JSON.parse(event.data)
}
}
onMounted(() => {
initSSE();
});
onUnmounted(() => {
sse.value.close()
});總結(jié)
到此這篇關(guān)于前端vue3使用SSE、EventSource攜帶請(qǐng)求頭的文章就介紹到這了,更多相關(guān)前端vue3 SSE攜帶請(qǐng)求頭內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
element el-table表格的二次封裝實(shí)現(xiàn)(附表格高度自適應(yīng))
這篇文章主要介紹了element el-table表格的二次封裝實(shí)現(xiàn)(附表格高度自適應(yīng)),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Vue3+element實(shí)現(xiàn)表格數(shù)據(jù)導(dǎo)出
這篇文章主要為大家學(xué)習(xí)介紹了Vue3如何利用element實(shí)現(xiàn)表格數(shù)據(jù)導(dǎo)出功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴快跟隨小編一起學(xué)習(xí)一下吧2023-07-07
vue中this.$refs.name.offsetHeight獲取不到值問(wèn)題
這篇文章主要介紹了vue中this.$refs.name.offsetHeight獲取不到值問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05
vue-baidu-map實(shí)現(xiàn)區(qū)域圈線和路徑的漸變色
這篇文章主要介紹了vue-baidu-map實(shí)現(xiàn)區(qū)域圈線和路徑的漸變色方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
vue中項(xiàng)目頁(yè)面空白但不報(bào)錯(cuò)產(chǎn)生的原因及分析
這篇文章主要介紹了vue中項(xiàng)目頁(yè)面空白但不報(bào)錯(cuò)產(chǎn)生的原因及分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05
淺談vue2 單頁(yè)面如何設(shè)置網(wǎng)頁(yè)title
這篇文章主要介紹了淺談vue2 單頁(yè)面如何設(shè)置網(wǎng)頁(yè)title,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-11-11

