HTML5 服務(wù)器發(fā)送事件(Server-Sent Events)使用詳解
正文:
HTML5服務(wù)器發(fā)送事件(server-sent event)允許網(wǎng)頁(yè)獲得來(lái)自服務(wù)器的更新
EventSource是單向通信的(是服務(wù)器向客戶端的單向通信,客戶端接收來(lái)自服務(wù)器的事件流)、基于HTTP協(xié)議(EventSource是基于標(biāo)準(zhǔn)的HTTP/HTTPS協(xié)議),使用長(zhǎng)輪詢或類似的機(jī)制,但并不是完全雙向的通信、文本數(shù)據(jù)傳輸(通常用于傳輸文本數(shù)據(jù),如服務(wù)器推送的消息或事件)、自動(dòng)重連(當(dāng)連接中斷,EventSource會(huì)自動(dòng)嘗試重新連接,不需要手動(dòng)處理重連)。
使用場(chǎng)景:
適合需要從服務(wù)器獲取實(shí)時(shí)信息的應(yīng)用,例如股票行情或新聞推送。
使用方式:
1、直接使用瀏覽器自帶EventSource,缺點(diǎn):不可以自定義參數(shù)且只能get方式請(qǐng)求,無(wú)法向服務(wù)端傳遞請(qǐng)求參數(shù),比如請(qǐng)求頭中攜帶token
if (window.hasOwnProperty("EventSource")) {
// url 接口
let source = new EventSource(
"https://api.baichuan-ai.com/v1/chat/completions"
);
// 當(dāng)發(fā)生錯(cuò)誤
source.onerror = function () {
console.log("error");
};
// 當(dāng)通往服務(wù)器的連接被打開(kāi)
source.onopen = function () {
console.log("連接成功");
};
// 當(dāng)接收到消息
source.onmessage = function (event) {
console.log("服務(wù)器推送數(shù)據(jù)", event.data);
};
}2、使用 EventSourcePolyfill ,解決使用EventSource無(wú)法在header中傳參,缺點(diǎn):只能get請(qǐng)求且無(wú)法向服務(wù)端傳遞請(qǐng)求參數(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ā)生錯(cuò)誤
source.onerror = function () {
console.log("error");
};
// 當(dāng)通往服務(wù)器的連接被打開(kāi)
source.onopen = function () {
console.log("連接成功");
};
// 當(dāng)接收到消息
source.onmessage = function (event) {
console.log("服務(wù)器推送數(shù)據(jù)", event.data);
};3、使用fetchEventSource,實(shí)現(xiàn)post請(qǐng)求方式
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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!
相關(guān)文章
淺談HTML5 服務(wù)器推送事件(Server-sent Events)
這篇文章主要介紹了淺談HTML5 服務(wù)器推送事件(Server-sent Events) ,具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-01HTML5 文件域+FileReader 分段讀取文件并上傳到服務(wù)器
這篇文章主要介紹了HTML5 文件域+FileReader 分段讀取文件并上傳到服務(wù)器,需要的朋友可以參考下2017-10-23
淺談html5之sse服務(wù)器發(fā)送事件EventSource介紹
本篇文章主要介紹了淺談html5之sse服務(wù)器發(fā)送事件EventSource介紹,具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-28- 這篇文章主要介紹了淺析HTML5的WebSocket與服務(wù)器推送事件,WebSocket API最大的特點(diǎn)就是讓服務(wù)器和客戶端能在給定的時(shí)間范圍內(nèi)的任意時(shí)刻,相互推送信息,需要的朋友可以參2016-02-19


