EventSource在前端项目中的使用

1.什么是EventSource?

EventSource(也称Server-Sent Event,简称SSE)是HTML5中用于实现服务器向客户端推送事件的浏览器API。允许客户端(浏览器)通过一个持久的HTTP连接,实时接收服务器的数据更新。

核心概念:

  • 单向通信:服务器单向向客户端推送数据,客户端智能监听事件(如需双向通信可使用webSocket)
  • 基于HTTP:使用简单的HTTP协议,兼容现有基础设施
  • 轻量级:协议简单,适合文本数据(json,纯文本)

2.怎么去使用EventSource

(1)使用get请求方式

不需要插件,直接使用EventSource创建对象,通过该对象连接服务器,并接收服务器推送的消息

 // 创建一个EventSource对象,并传入连接服务器地址
    const evnetSource = new EventSource("https://yourgeturl")
        //连接后刚打开触发
    eventSource.onopen = (e) => {
            console.log("连接刚打开触发", e)
        }
        //接收服务器推送消息
    eventSource.onmessage = (e) => {
            console.log("接收到的消息", e)
        }
        //连接失败
    eventSource.onerror = (e) => {
        console.log("连接失败", e)
        eventSource.close()
    }

    //关闭连接
    eventSource.close()

(2)使用post请求方式

使用post请求eventSource,需要借助第三方库fetchEventSource方式去连接服务,利用AbortController对象关闭服务

安装fetch-event-source

npm install --save @microsoft/fetch-event-source

使用fetch-event-source

const controller = new AbortController();
 const { signal } = controller;
fetchEventSource(url, {
            method: "POST" //请求方式,post
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'text/event-stream'
            }, //请求头部
            body: JSON.stringify(data), //请求内容参数
            signal: signal, //中断请求
            openWhenHidden: true, //后台保活
            onopen: (e) => {
                if (e.ok) {
                    console.log("连接成功", e)
                } else {
                    console.log("连接失败", e)
                }
            },
            onclose: (close) => {
                console.log("连接关闭", close)
            },
            onerror: (err) => {
                console.log("连接错误", err)
            },
            onmessage: (data) => {
                console.log("接收到的消息", data)
            }
        })

使用需要中断使用AbortController进行中断

controller.abort();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值