一、认识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();
}
})