SSE初體驗(yàn)

最近看到的,記錄一下,SSE長連接

什么是SSE?

SSE(Sever-Sent Event),就是瀏覽器向服務(wù)器發(fā)送了一個(gè)HTTP請求,保持長連接,服務(wù)器不斷單向地向?yàn)g覽器推送“信息”,這么做是為了節(jié)省網(wǎng)絡(luò)資源,不用一直發(fā)請求,建立新連接。
是一種服務(wù)端向客戶端推送信息的單向通信方法

EventSource

1.SSE具有由 W3C 標(biāo)準(zhǔn)化的網(wǎng)絡(luò)協(xié)議
2.EventSource 是SSE客戶端接口
3.EventSource不支持headers參數(shù)
4.使用EventSource傳輸,傳輸內(nèi)容一定是text/event-stream的,即后臺(tái)要設(shè)置返回的content-type為text/event-stream

上代碼

import React, { useEffect, useRef, useState } from "react";

const readyStateArr = [
    { key: 0, value: "0 連接尚未建立,或已關(guān)閉且客戶端正在重新連接" },
    { key: 1, value: "戶端有一個(gè)打開的連接并在接收到事件時(shí)處理它們" },
    { key: 2, value: "連接未打開,并且客戶端未嘗試重新連接,要么出現(xiàn)致命錯(cuò)誤,要么調(diào)用了 close() 方法" },
];

const useSSE = () => {
    const source = useRef<EventSource | null>(null);
    const [sseData, setSseData] = useState({});
    const [sseReadyState, setSseReadyState] = useState({
        key: 0,
        value: "正在鏈接中",
    });

    const createSSE = () => {
        try {
            source.current = new EventSource("https://test/sse");
            source.current.onopen = (e) => {
                setSseReadyState(readyStateArr[source.current?.readyState ?? 0]);
            };
            source.current.onerror = (e) => {
                setSseReadyState(readyStateArr[source.current?.readyState ?? 0]);
            };
            source.current.onmessage = (e) => {
                setSseData({ ...JSON.parse(e.data) });
            };
        } catch (error) {
            console.log(error);
        }
    };

    const initSSE = () => {
        if (!source.current || source.current.readyState === 2) {
            createSSE();
        }
    };

    const closeSSE = () => {
        source.current?.close();
    };

    const reconnectSSE = () => {
        try {
            closeSSE();
            source.current = null;
            createSSE();
        } catch (error) {
            console.log(error);
        }
    };

    useEffect(() => {
        initSSE();
    }, []);

    return {
        sseData,
        sseReadyState,
        closeSSE,
        reconnectSSE,
    };
};

export default useSSE;

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容