SSE 与 WebSocket 作用相似,都是建立浏览器与服务器之间的通信渠道,然后服务器向浏览器推送信息SSE 是单向通道,只能服务器向浏览器发送,因为流信息本质上就是下载。如果浏览器向服务器发送信息,就变成了另一次 HTTP 请求
使用方法
Server-Sent Events 教程 - 阮一峰的网络日志https://www.ruanyifeng.com/blog/2017/05/server-sent_events.html
缺点:不可以比如请求头中加token等
getSSE() {
return new Promise((resolve, reject) => {
let base = process.env.VUE_APP_SYSTEMURL;
let url = `${base}/server/sampleRemovePush/sse`;
if (window.EventSource) {
this.SSE = new EventSource(url);
this.SSE.addEventListener(
"open",
e => {
console.log("建立连接。。。", e);
},
false
);
this.SSE.addEventListener(
"message",
event => {
console.log("ebent", event);
resolve(event);
},
false
);
this.SSE.addEventListener(
"error",
event => {
// readyState连接状态: 0 - connecting; 1 - open; 2 - closed;
if ((event.readyState = EventSource.CLOSED)) {
console.log("sse错误------", event);
reject("请求错误!");
} else {
resolve(event);
}
},
false
);
// this.SSE.addEventListener("close", event => {
// console.log("我要关闭啦", event.type);
// this.SSE.close();
// });
} else {
console.log("你的浏览器不支持SSE");
}
});
},
如果加自定义参数可以使用三方插件event-source-polyfill
GitHub - Yaffle/EventSource: a polyfill for http://www.w3.org/TR/eventsource/a polyfill for http://www.w3.org/TR/eventsource/. Contribute to Yaffle/EventSource development by creating an account on GitHub.https://github.com/Yaffle/EventSource/使用方法
npm install event-source-polyfill
import {EventSourcePolyfill} from 'event-source-polyfill';
let base = process.env.VUE_APP_SYSTEMURL;
let url = `${base}/server/sampleRemovePush/sse`;
let { access_token } = this.$store.state.login.login;
var es = new EventSourcePolyfill(url, {
headers: {
Authorization: access_token ? `Bearer${access_token}` : ""
}
});
es.onopen = function(event) {
console.log("连接成功", event);
};
es.onmessage = function(event) {
// to to something…
console.log("接收信息", event);
};
es.onerror = function(error) {
// 监听错误
console.log("错误", error);
};
可 以看到token是有加上去的 文章来源:https://www.toymoban.com/news/detail-660455.html
文章来源地址https://www.toymoban.com/news/detail-660455.html
到了这里,关于Server-Sent Events(以下简称 SSE)及event-source-polyfill使用单向长连接(后台主动向前端推送)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!