vue + webSocket 實(shí)時(shí)任務(wù)信息通知
websocket
WebSocket 協(xié)議在2008年誕生腰涧,2011年成為國(guó)際標(biāo)準(zhǔn)清焕。所有瀏覽器都已經(jīng)支持了罕模。
它的最大特點(diǎn)就是,服務(wù)器可以主動(dòng)向客戶端推送信息杈女,客戶端也可以主動(dòng)向服務(wù)器發(fā)送信息,是真正的雙向平等對(duì)話,屬于服務(wù)器推送技術(shù)的一種达椰。
特點(diǎn)
- 建立在TCP協(xié)議之上翰蠢,服務(wù)端的實(shí)現(xiàn)比較容易;
- 與HTTP協(xié)議有著良好的兼容性啰劲。默認(rèn)端口也是80和443梁沧,并且握手階段采用HTTP協(xié)議,因此握手時(shí)不容易屏蔽蝇裤,能通過各種HTTP代理服務(wù)器廷支;
- 數(shù)據(jù)格式比較輕量,性能開銷小栓辜,通信高效恋拍;
- 可以發(fā)送文本,也可以發(fā)送二進(jìn)制數(shù)據(jù)
- 沒有同源限制藕甩,客戶端可以與任意服務(wù)器通信
- 協(xié)議標(biāo)識(shí)符是 WS(如果加密施敢,則為WSS),服務(wù)器網(wǎng)址就是URL
image
VUE + WebSocket 長(zhǎng)鏈接實(shí)現(xiàn)
在項(xiàng)目的創(chuàng)建 utils/websocket.js
<!--引入store狭莱,用于管理socket推送來的消息-->
import store from '../store'
<!--封裝websocket對(duì)象-->
const WS = {
$ws:null, // webscoket實(shí)例
wsUrl: 'ws://xxxxx.com:80/xxx', // websocket鏈接地址
<!--初始化webSocket-->
createWS:function(){
if('WebSocket' in window){
this.$ws = new WebSocket(wsURl)
this.$ws.onopen = this.wsOpen
this.$ws.onmessage = this.wsMessage
this.$ws.onerror = this.wsError
this.$ws.onclose = this.wsClose
} else {
alert('當(dāng)前瀏覽器不支持webSocket')
}
},
<!--webSocket 打開-->
wsOpen: function() {
this.$ws.send('連接成功')
console.log('== websocket open ==')
<!--開始心跳-->
heartBeat.start()
},
<!--websocket 接收到服務(wù)器消息-->
wsMessage:function(msg) {
console.log('== websocket message ==', msg)
<!--接受到消息僵娃,重置心跳-->
heartBeat.reset()
store.commit('SET_WS_MSG', msg.data)
},
<!--websocket 發(fā)生錯(cuò)誤-->
wsError: function(err){
console.log('== websocket error ==', err)
},
<!--websocket 關(guān)閉連接-->
wsClose: function(event){
console.log('== websocket close ==', event)
}
}
<!--webSocket 心跳-->
const heartBeat = {
timeout:30000, // 心跳重連時(shí)間
timeoutObj:null, // 定時(shí)器
reset:function(){
clearInterVal(this.timeoutObj)
console.log('websocket 心跳')
WS.start()
},
start:function(){
this.timeoutObj = setTimeout(function(){
if(WS.$ws.readyState === 1){
WS.$ws.send('HeartBeat')
}
},this.timeout)
}
}
export default WS
在main.js中引入WS,掛載到Vue原型上
import Vue from 'vue'
import WS from '@/util/websocket'
Vue.prototype.$ws = WS
在store/index.js創(chuàng)建全局?jǐn)?shù)據(jù)存儲(chǔ)
const store= new Vuex.Store({
state:{
webSocketMsg:''
},
mutations:{
SET_WS_MSG (state, msg) =>{
state.webSocketMsg = msg
}
}
})
在單個(gè)組件內(nèi)部使用
computed:{
getWsMsg (){
return this.$store.state.webSocketMsg
}
},
watch:{
getWsMsg:{
handler: function(newVal) {
console.log(newVal)
alert('接收到webSocket推送'+ newVal)
}
}
}
如果要在所有的界面都能接收socket推送消息贩毕,并彈出提示可以在布局組件(Layout.vue ...)中監(jiān)聽
computed:{
getWsMsg (){
return this.$store.state.webSocketMsg
}
},
watch:{
getWsMsg:{
handler: function(newVal) {
console.log(newVal)
alert('接收到webSocket推送'+ newVal)
}
}
}
參考文檔
作者:Beppo
鏈接:http://www.reibang.com/p/fe8bd81814b0
來源:簡(jiǎn)書