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)文章
淺談HTML5 服務(wù)器推送事件(Server-sent Events)
這篇文章主要介紹了淺談HTML5 服務(wù)器推送事件(Server-sent Events) ,具有一定的參考價值,有興趣的可以了解一下2017-08-01HTML5 文件域+FileReader 分段讀取文件并上傳到服務(wù)器
這篇文章主要介紹了HTML5 文件域+FileReader 分段讀取文件并上傳到服務(wù)器,需要的朋友可以參考下2017-10-23淺談html5之sse服務(wù)器發(fā)送事件EventSource介紹
本篇文章主要介紹了淺談html5之sse服務(wù)器發(fā)送事件EventSource介紹,具有一定的參考價值,有興趣的可以了解一下2017-08-28- 這篇文章主要介紹了淺析HTML5的WebSocket與服務(wù)器推送事件,WebSocket API最大的特點(diǎn)就是讓服務(wù)器和客戶端能在給定的時間范圍內(nèi)的任意時刻,相互推送信息,需要的朋友可以參2016-02-19