首页 前端知识 HTML5 服务器发送事件(Server-Sent Events)

HTML5 服务器发送事件(Server-Sent Events)

2024-02-04 11:02:52 前端知识 前端哥 692 930 我要收藏

前言:

       文章内容参考:

                                HTML5 服务器发送事件(Server-Sent Events) | 菜鸟教程

                                @microsoft/fetch-event-source - npm

                                event-source-polyfill - npm

正文:

        HTML5服务器发送事件(server-sent event)允许网页获得来自服务器的更新

        EventSource是单向通信的(是服务器向客户端的单向通信,客户端接收来自服务器的事件流)、基于HTTP协议(EventSource是基于标准的HTTP/HTTPS协议),使用长轮询或类似的机制,但并不是完全双向的通信、文本数据传输(通常用于传输文本数据,如服务器推送的消息或事件)、自动重连(当连接中断,EventSource会自动尝试重新连接,不需要手动处理重连)。

       使用场景:适合需要从服务器获取实时信息的应用,例如股票行情或新闻推送。

 使用方式:

  1、直接使用浏览器自带EventSource,缺点:不可以自定义参数且只能get方式请求,无法向服务端传递请求参数,比如请求头中携带token

if (window.hasOwnProperty("EventSource")) {
// url 接口
let source = new EventSource(
"https://api.baichuan-ai.com/v1/chat/completions"
);
// 当发生错误
source.onerror = function () {
console.log("error");
};
// 当通往服务器的连接被打开
source.onopen = function () {
console.log("连接成功");
};
// 当接收到消息
source.onmessage = function (event) {
console.log("服务器推送数据", event.data);
};
}
复制

2、使用 EventSourcePolyfill ,解决使用EventSource无法在header中传参,缺点:只能get请求且无法向服务端传递请求参数

import { EventSourcePolyfill } from "event-source-polyfill";
// url 接口
let source = new EventSourcePolyfill(
"https://api.baichuan-ai.com/v1/chat/completions",
{
headers: {
Authorization: "token",
},
}
);
// 当发生错误
source.onerror = function () {
console.log("error");
};
// 当通往服务器的连接被打开
source.onopen = function () {
console.log("连接成功");
};
// 当接收到消息
source.onmessage = function (event) {
console.log("服务器推送数据", event.data);
};
复制

3、使用fetchEventSource,实现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",
// 参数
body: JSON.stringify({
username: "LIIIIII",
password: "123456",
}),
onmessage(event) {
console.log(event.data);
},
onerror() {
console.log("erroe");
},
}
);
复制

转载请注明出处或者链接地址:https://www.qianduange.cn//article/1266.html
标签
评论
还可以输入200
共0条数据,当前/页
会员中心 联系我 留言建议 回顶部
复制成功!