赞
踩
server send event简称sse,也就是我们所说的sse技术。是es5提出的一种基于http协议的服务器推送技术。与websocket类似,与服务器构建通道后,服务器可以实时主动向客户端发送信息。且sse本身只能支持Get请求,如果需要post请求的场景,可以引入或安装第三方组件解决。
比如可以通过fetch的方式完成post相关操作。开源组件:GitHub - Azure/fetch-event-source: A better API for making Event Source requests, with all the features of fetch()
特点:
单向通道:sse是单向通道协议,只能通过服务器向客户端发送信息。
长连接:通过向服务器发送请求,在响应头中声明Content-Type:text/event-stream向服务器说明这是一个长链接,发送的是流数据。
实时性:与websocket相同,客户端可以通过sse实时接收服务器发送的信息,可以应用于需要实时更新数据的应用场景。
兼容性:(取自 Can I use... Support tables for HTML5, CSS3, etc)
基本上能看出,除了IE浏览器,其他浏览器基本都可以支持-_-||
代码:
- // Get请求
- const sse = new EventSource('http://xxxxxxxxx');
-
- // SSE只能监听预定义事件,无法监听自定义事件。
-
- // 开启
- sse.onopen = (ev) => {
- // 可以在当前事件中监听通道开启,同时通道构建失败时,也可以通过当前事件监听到,比如http码报错。
- console.log(ev.data);
- };
-
- // 更新
- sse.onmessage = (ev) => {
- console.log(ev.data);
- };
-
- // 关闭
- sse.onclose = (ev) => {
- console.log(ev.data);
- };
-
- // 错误
- sse.onerror = (ev) => {
- console.log(ev.data);
- };

- // 运用第三方开源组件实现post请求
- import { fetchEventSource } from '@microsoft/fetch-event-source';
-
- const ctrlAbout: any = ref(null);
-
- fetchEventSource('http://xxxxxxxxxxx', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- Accept: 'text/event-stream',
- ...
- },
- signal: ctrlAbout.value.signal,
- body: JSON.stringify({
- id: '1',
- text: '这是发送的信息'
- }),
-
- async onopen(eva: any) {
- console.log('开启', eva);
-
- // 可以判断token是否过期
- if (eva.status === 401 || eva.status === xxx) {
- console.log('用户信息过期,请重新登陆!');
- }
- },
-
- onmessage(eva: any) {
- console.log('更新', eva);
- },
-
- onclose() {
- console.log('断开');
- },
-
- onerror(err: any) {
- console.log('错误', err);
- }
- });
-
- // 关闭sse
- function close() {
- ctrlAbout.value.abort();
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。