前端實現(xiàn)簡單的sse封裝方式(React hook Vue3)
更新時間:2024年08月29日 09:27:25 作者:bigHead-
這篇文章主要介紹了前端實現(xiàn)簡單的sse封裝方式(React hook Vue3),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
什么是SSE?
所謂的SSE(Sever-Sent Event),就是瀏覽器向服務器發(fā)送了一個HTTP請求,保持長連接,服務器不斷單向地向瀏覽器推送“信息”,這么做是為了節(jié)省網(wǎng)絡資源,不用一直發(fā)請求,建立新連接。
- 優(yōu)點:SSE和WebSocket相比,最大的優(yōu)勢是便利,服務端不需要第三方組件,開發(fā)難度低,SSE和輪詢相比它不用處理很多請求,不用每次建立新連接,延遲低。
- 缺點:如果客戶端有很多需要保持很多長連接,這回占用大量內(nèi)存和連接數(shù)。
封裝簡單的SSE,以React hook為例
新建sse.ts文件
import {useState, useRef, useEffect} from 'react' const useSSE = (url: string) => { const source = useRef<EventSource | null>(null) //接收到的sse數(shù)據(jù) const [sseData, setSseData] = useState({}) // sse狀態(tài) const [sseReadyState, setSseReadyState] = useState({ key: 0, value: '正在鏈接中', }) const creatSource = () => { const stateArr = [ {key: 0, value: '正在鏈接中'}, {key: 1, value: '已經(jīng)鏈接并且可以通訊'}, {key: 2, value: '連接已關閉或者沒有鏈接成功'}, ] try { source.current = new EventSource(url) source.current.onopen = (_e) => { setSseReadyState(stateArr[source.current?.readyState ?? 0]) } source.current.onerror = (e) => { setSseReadyState(stateArr[source.current?.readyState ?? 0]) } source.current.onmessage = (e) => { setSseData({...JSON.parse(e.data)}) } } catch (error) { console.log(error) } } const sourceInit = () => { if (!source.current || source.current.readyState === 2) { creatSource() } } // 關閉 WebSocket const closeSource = () => { source.current?.close() } //重連 const reconnectSSE = () => { try { closeSource() source.current = null creatSource() } catch (e) { console.log(e) } } useEffect(() => { sourceInit() },[]) return { sseData, sseReadyState, closeSource, reconnectSSE, } } export default useSSE
這里一共暴露出四個參數(shù)。
分別是 sseData(接收到的 sse數(shù)據(jù))、sseReadyState(當前 sse狀態(tài))、closeSource(關閉 sse)、reconnectSSE(重連)。
通過這幾個簡單的參數(shù)能夠覆蓋一般場景的需要。
下面代碼為使用方法
import React, { useState, useEffect } from 'react' import useWebsocket from '../../tools/webSocket' export default function () { const {sseData,sseReadyState, closeSource,reconnectSSE} = useSSE(url) useEffect(() => { console.log( '當前狀態(tài)',sseReadyState) },[sseReadyState]) useEffect(() => { console.log( '接收到的數(shù)據(jù)',sseData) }, [sseData]) }
使用vue3實現(xiàn)
import { ref } from "vue"; const useSSE = (url: string) => { const source = ref<EventSource | null>(null); //接收到的sse數(shù)據(jù) const sseData = ref({}); // sse狀態(tài) const readyState = ref({ key: 0, value: "正在鏈接中" }); const creatSource = () => { const stateArr = [ { key: 0, value: "正在鏈接中" }, { key: 1, value: "已經(jīng)鏈接并且可以通訊" }, { key: 2, value: "連接已關閉或者沒有鏈接成功" }, ]; try { source.value= new EventSource(url); source.value.onopen = (e) => { readyState.value = stateArr[source.value?.readyState ?? 0]; }; source.value.onerror = (e) => { readyState.value = stateArr[source.value?.readyState ?? 0]; }; source.value.onmessage = (e) => { e.data && (sseData.value = { ...JSON.parse(e.data) }); }; } catch (error) { console.log(error); } }; const sourceInit = () => { if (!source.value|| source.value.readyState === 2) { creatSource(); } }; // 關閉 WebSocket const closeSource = () => { source.value?.close(); }; //重連 const reconnectSSE = () => { try { closeSource(); source.value= null; creatSource(); } catch (e) { console.log(e); } }; return { sseData, readyState, sourceInit, closeSource, reconnectSSE, }; }; export default useSSE;
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue使用localStorage保存登錄信息 適用于移動端、PC端
這篇文章主要為大家詳細介紹了vue使用localStorage保存登錄信息 適用于移動端、PC端,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-05-05Vue實現(xiàn)網(wǎng)頁轉(zhuǎn)PDF方法流程詳解
在日常的工作中,有時候會碰到需要將某個網(wǎng)址網(wǎng)頁保存成為pdf的情況,這篇文章主要介紹了用Vue實現(xiàn)網(wǎng)頁轉(zhuǎn)PDF的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08