EventSource 在项目中常用的两种方式

一、认识EventSource 

EventSource(也称为Server-Sent Events,简称SSE)是HTML5中的一种新的API,用于实现服务器端向客户端推送事件。其数据主要基于HTTP协议进行传输,并且数据帧必须编码成UTF-8的格式。

eventSource是单向通信的,只能从服务器端向客户端发送数据。如果你需要双向通信(即客户端和服务器之间可以相互发送数据),那么你可能需要使用WebSocket或其他技术。

二、项目中使用

而 eventSource 只能由服务器向客户端发送消息,项目中常用的请求方式又get和post方式,对于没有请求要求的情况,短文本的情况使用浏览器提供的api即可。

1.使用get方式

不需要安装插件,直接创建EventSource对象,通过EventSource对象连接服务,连接服务以后就可以接受服务推送的消息。

 //定义一个EventSource对象,传入请求地址URL
 const eventSource = new EventSource('url')
  
  // 与事件源的连接刚打开时触发
  eventSource.onopen = function (e) {
       console.log(e, "连接刚打开时触发");
  };

  // 后端返回信息,格式可以和后端协商
   eventSource.onmessage = function (e) {
     console.log(e);
   };

  // 连接失败
   eventSource.onerror = function (e) {
     console.log(e);
     eventSource.close(); // 关闭连接
  };

  // 关闭连接
  eventSource.close();   

注意:使用浏览器提供的本地EventSource服务,无法获取连接状态编码。

2.使用post方式请求

使用post的方式请求eventSource,常用的就是通过fetchEventSource这个库来实现,借助第三方库的fetchEventSource方法连接服务,通过AbortController 对象可以关闭服务

安装fetch-event-source插件

npm i --save @rangermauve/fetch-event-source

本地使用fetch-event-source

import { fetchEventSource } from '@microsoft/fetch-event-source';
 
 const ctrlAbout = new AbortController();
 const eventSource = fetchEventSource(Url, {
   method: 'POST',
   headers: {
     "Content-Type": 'application/json',
     "Accept": 'text/event-stream'
   },
   body: JSON.stringify(data),
   onmessage(event) {
      console.info(event.data);
      // 在这里操作流式数据
   },
   onerror(error) {
       console.info(error);
       //关闭流
       ctrlAbout.abort();
   }
 })

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值