当前位置: 代码网 > it编程>网页制作>html5 > HTML5 服务器发送事件(Server-Sent Events)使用详解

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

2024年05月15日 html5 我要评论
HTML5 服务器发送事件(Server-Sent Events)使用详解HTML5服务器发送事件(server-sent event)允许网页获得来自服务器的更新,下面通过本文给大家介绍HTML5 服务器发送事件(Server-Sent Events)使用详解,感兴趣的朋友跟随小编一起看看... 24-05-15

正文:

        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 服务器发送事件内容请搜索代码网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com