vue2中使用SSE(服務器發(fā)送事件)原因分析
SSE簡介
SSE(Server-Sent Events,服務器發(fā)送事件)是圍繞只讀Comet 交互推出的API 或者模式。
SSE API允許網頁獲得來自服務器的更新,用于創(chuàng)建到服務器的單向連接,服務器通過這個連接可以發(fā)送任意數(shù)量的數(shù)據(jù)。服務器響應的MIME類型必須是text/event-stream,而且是瀏覽器中的JavaScript API 能解析格式輸出。

SSE 支持短輪詢、長輪詢和HTTP 流,而且能在斷開連接時自動確定何時重新連接。
使用原因
之前系統(tǒng)通知公告等信息是通過每隔一段時間調用接口來判斷是否有新的公告或通知,最開始想到的是用websocket,但是這場景只需要服務端往客戶端發(fā)送消息,所以商量后決定使用SSE。
// 使用這個庫可以添加的請求頭(比如添加token)
import { EventSourcePolyfill } from "event-source-polyfill";
import { getToken } from '@/utils/user'
export default {
data() {
return {
eventSource: null
}
},
mounted() {
this.createSSE()
},
methods: {
createSSE(){
if(window.EventSource){
// 根據(jù)環(huán)境的不同,變更url
const url = process.env.VUE_APP_MSG_SERVER_URL
// 用戶userId
const { userId } = this.$store.state.user
this.eventSource = new EventSourcePolyfill(
`${url}/sse/connect/${userId}`, {
// 設置重連時間
heartbeatTimeout: 60 * 60 * 1000,
// 添加token
headers: {
'Authorization': `Bearer ${getToken()}`,
},
});
this.eventSource.onopen = (e) => {
console.log("已建立SSE連接~")
}
this.eventSource.onmessage = (e) => {
console.log("已接受到消息:", e.data)
}
this.eventSource.onerror = (e) => {
if (e.readyState == EventSource.CLOSED) {
console.log("SSE連接關閉");
} else if (this.eventSource.readyState == EventSource.CONNECTING) {
console.log("SSE正在重連");
//重新設置token
this.eventSource.headers = {
'Authorization': `Bearer ${getToken()}`
};
} else {
console.log('error', e);
}
};
} else {
console.log("你的瀏覽器不支持SSE~")
}
},
beforeDestroy() {
if(this.eventSource){
const { userId } = this.$store.state.user
// 關閉SSE
this.eventSource.close();
// 通知后端關閉連接
this.$API.system.msg.closeSse(userId)
this.eventSource = null
console.log("退出登錄或關閉瀏覽器,關閉SSE連接~")
}
},在createSSE被調用后,這個請求會一直在pending狀態(tài)

直到服務端向客戶端發(fā)送消息,狀態(tài)才會改變

最后離開時記得關閉連接

到此這篇關于在vue2中使用SSE(服務器發(fā)送事件)的文章就介紹到這了,更多相關vue2使用SSE內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
VUEX 數(shù)據(jù)持久化,刷新后重新獲取的例子
今天小編就為大家分享一篇VUEX 數(shù)據(jù)持久化,刷新后重新獲取的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
vue實現(xiàn)將數(shù)據(jù)存入vuex中以及從vuex中取出數(shù)據(jù)
今天小編就為大家分享一篇vue實現(xiàn)將數(shù)據(jù)存入vuex中以及從vuex中取出數(shù)據(jù),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11

