欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

HTML5 服務(wù)器發(fā)送事件(Server-Sent Events)使用詳解

  發(fā)布時間:2024-05-15 16:55:05   作者:Lee_Yu_Fan   我要評論
HTML5服務(wù)器發(fā)送事件(server-sent event)允許網(wǎng)頁獲得來自服務(wù)器的更新,下面通過本文給大家介紹HTML5 服務(wù)器發(fā)送事件(Server-Sent Events)使用詳解,感興趣的朋友跟隨小編一起看看吧

正文:

        HTML5服務(wù)器發(fā)送事件(server-sent event)允許網(wǎng)頁獲得來自服務(wù)器的更新

        EventSource是單向通信的(是服務(wù)器向客戶端的單向通信,客戶端接收來自服務(wù)器的事件流)、基于HTTP協(xié)議(EventSource是基于標(biāo)準(zhǔn)的HTTP/HTTPS協(xié)議),使用長輪詢或類似的機(jī)制,但并不是完全雙向的通信、文本數(shù)據(jù)傳輸(通常用于傳輸文本數(shù)據(jù),如服務(wù)器推送的消息或事件)、自動重連(當(dāng)連接中斷,EventSource會自動嘗試重新連接,不需要手動處理重連)。

使用場景:

適合需要從服務(wù)器獲取實(shí)時信息的應(yīng)用,例如股票行情或新聞推送。

 使用方式:

  1、直接使用瀏覽器自帶EventSource,缺點(diǎn):不可以自定義參數(shù)且只能get方式請求,無法向服務(wù)端傳遞請求參數(shù),比如請求頭中攜帶token

 if (window.hasOwnProperty("EventSource")) {
    // url 接口
    let source = new EventSource(
      "https://api.baichuan-ai.com/v1/chat/completions"
    );
    // 當(dāng)發(fā)生錯誤
    source.onerror = function () {
      console.log("error");
    };
    // 當(dāng)通往服務(wù)器的連接被打開
    source.onopen = function () {
      console.log("連接成功");
    };
    // 當(dāng)接收到消息
    source.onmessage = function (event) {
      console.log("服務(wù)器推送數(shù)據(jù)", event.data);
    };
  }

2、使用 EventSourcePolyfill ,解決使用EventSource無法在header中傳參,缺點(diǎn):只能get請求且無法向服務(wù)端傳遞請求參數(shù)

  import { EventSourcePolyfill } from "event-source-polyfill";
  // url 接口
  let source = new EventSourcePolyfill(
    "https://api.baichuan-ai.com/v1/chat/completions",
    {
      headers: {
        Authorization: "token",
      },
    }
  );
  // 當(dāng)發(fā)生錯誤
  source.onerror = function () {
    console.log("error");
  };
  // 當(dāng)通往服務(wù)器的連接被打開
  source.onopen = function () {
    console.log("連接成功");
  };
  // 當(dāng)接收到消息
  source.onmessage = function (event) {
    console.log("服務(wù)器推送數(shù)據(jù)", event.data);
  };

3、使用fetchEventSource,實(shí)現(xiàn)post請求方式

import { fetchEventSource } from "@microsoft/fetch-event-source";
 let es = new fetchEventSource(
    "https://api.baichuan-ai.com/v1/chat/completions",
    {
      headers: {
        Authorization: "token值",
        withCredentials: true,
        "Content-Type": "application/json",
      },
      method: "post",
      // 參數(shù)
      body: JSON.stringify({
        username: "LIIIIII",
        password: "123456",
      }),
      onmessage(event) {
        console.log(event.data);
      },
      onerror() {
        console.log("erroe");
      },
    }
  );

到此這篇關(guān)于HTML5 服務(wù)器發(fā)送事件(Server-Sent Events)使用詳解的文章就介紹到這了,更多相關(guān)HTML5 服務(wù)器發(fā)送事件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論