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

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");
      },
    }
  );

以上就是关于 HTML5 服务器发送事件(Server-Sent Events)使用教程就介绍到这了。

详解 HTML5 服务器发送事件(Server-Sent Events)的使用教程-码云笔记HTML5服务器发送事件(server-sent event)允许网页获得来自服务器的更新。 EventSource是单向通信的(是服务器向客户端的单向通信,客户端接收来自服务器的事件流)、基于HTTP协议(EventSource是基于标准的HTTP/HTTPS协议),使用长轮...https://mybj123.com/21968.html

相关推荐
hugo_im几秒前
GrapesJS 完全指南:从零构建你的可视化拖拽编辑器
前端·javascript·前端框架
用户904706683571 分钟前
nuxt 路由一篇讲清楚
前端
盘子素1 分钟前
前端实现跳转子系统,但限制只能跳转一次
前端·javascript
Anita_Sun2 分钟前
Lodash 源码解读与原理分析 - Lodash 前世今生:设计原则与演进脉络
前端
爱吃羊的老虎5 分钟前
Streamlit:快速创建应用界面,无需了解 Web 开发
前端·python
满栀5857 分钟前
三级联动下拉框
开发语言·前端·jquery
杨超越luckly15 分钟前
HTML应用指南:利用GET请求获取网易云热歌榜
前端·python·html·数据可视化·网易云热榜
前端_yu小白15 分钟前
React实现Vue的watch和computed
前端·vue.js·react.js·watch·computed·hooks
多看书少吃饭18 分钟前
OnlyOffice 编辑器的实现及使用
前端·vue.js·编辑器
编程之路从0到125 分钟前
JSI入门指南
前端·c++·react native