Vue中使用及封裝websocket示例詳解
簡(jiǎn)單例子
<template>
<div class="test">
</div>
</template>
<script>
export default {
name : 'test',
data() {
return {
websock: null,
}
},
created() {
this.initWebSocket();
},
destroyed() {
this.websock.close() //離開路由之后斷開websocket連接
},
methods: {
initWebSocket(){ //初始化weosocket
const wsuri = "ws://127.0.0.1:8080";
this.websock = new WebSocket(wsuri);
this.websock.onmessage = this.websocketonmessage;
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onclose = this.websocketclose;
},
websocketonopen(){ //連接建立之后執(zhí)行send方法發(fā)送數(shù)據(jù)
let actions = {"test":"12345"};
this.websocketsend(JSON.stringify(actions));
},
websocketonerror(){//連接建立失敗重連
this.initWebSocket();
},
websocketonmessage(e){ //數(shù)據(jù)接收
const redata = JSON.parse(e.data);
},
websocketsend(Data){//數(shù)據(jù)發(fā)送
this.websock.send(Data);
},
websocketclose(e){ //關(guān)閉
console.log('斷開連接',e);
},
},
}
</script>
<style lang='less'>
</style>封裝后
創(chuàng)建websocket.js
let Socket = ''
let setIntervalWesocketPush = null
/**
* 建立websocket連接
* @param {string} url ws地址
*/
export const createSocket = url => {
Socket && Socket.close()
if (!Socket) {
console.log('建立websocket連接')
Socket = new WebSocket(url)
Socket.onopen = onopenWS
Socket.onmessage = onmessageWS
Socket.onerror = onerrorWS
Socket.onclose = oncloseWS
} else {
console.log('websocket已連接')
}
}
/**打開WS之后發(fā)送心跳 */
const onopenWS = () => {
sendPing()
}
/**連接失敗重連 */
const onerrorWS = () => {
Socket.close()
clearInterval(setIntervalWesocketPush)
console.log('連接失敗重連中')
if (Socket.readyState !== 3) {
Socket = null
createSocket()
}
}
/**WS數(shù)據(jù)接收統(tǒng)一處理 */
const onmessageWS = e => {
window.dispatchEvent(new CustomEvent('onmessageWS', {
detail: {
data: e.data
}
}))
}
/**
* 發(fā)送數(shù)據(jù)但連接未建立時(shí)進(jìn)行處理等待重發(fā)
* @param {any} message 需要發(fā)送的數(shù)據(jù)
*/
const connecting = message => {
setTimeout(() => {
if (Socket.readyState === 0) {
connecting(message)
} else {
Socket.send(JSON.stringify(message))
}
}, 1000)
}
/**
* 發(fā)送數(shù)據(jù)
* @param {any} message 需要發(fā)送的數(shù)據(jù)
*/
export const sendWSPush = message => {
if (Socket !== null && Socket.readyState === 3) {
Socket.close()
createSocket()
} else if (Socket.readyState === 1) {
Socket.send(JSON.stringify(message))
} else if (Socket.readyState === 0) {
connecting(message)
}
}
/**斷開重連 */
const oncloseWS = () => {
clearInterval(setIntervalWesocketPush)
console.log('websocket已斷開....正在嘗試重連')
if (Socket.readyState !== 2) {
Socket = null
createSocket()
}
}
/**發(fā)送心跳
* @param {number} time 心跳間隔毫秒 默認(rèn)5000
* @param {string} ping 心跳名稱 默認(rèn)字符串ping
*/
export const sendPing = (time = 5000, ping = 'ping') => {
clearInterval(setIntervalWesocketPush)
Socket.send(ping)
setIntervalWesocketPush = setInterval(() => {
Socket.send(ping)
}, time)
}下載 (也可復(fù)制源碼,放在本地,使用方式相同)
npm install @sven0706/websocket -S
使用
// 在main.js或需要使用的地方引入并建立連接
import { createSocket } from '@sven0706/websocket'
createSocket('wss://api.baidu.com')
// 發(fā)送消息
import { sendWSPush } from '@sven0706/websocket'
sendWSPush(data)
// 接收消息
const getsocketData = e => { // 創(chuàng)建接收消息函數(shù)
const data = e && e.detail.data
console.log(data)
}
// 注冊(cè)監(jiān)聽事件
window.addEventListener('onmessageWS', getsocketData)
// 在需要的時(shí)候卸載監(jiān)聽事件,比如離開頁(yè)面
window.removeEventListener('onmessageWS', getsocketData)API
僅三個(gè)api, 且一般只需要用到`createSocket`, `sendWSPush`
/**
* 建立websocket連接
* @param {string} url ws地址
*/
createSocket(url)
/**
* 發(fā)送數(shù)據(jù)
* @param {any} message 需要發(fā)送的數(shù)據(jù)
*/
sendWSPush(message)
/**發(fā)送心跳
* @param {number} time 心跳間隔毫秒 默認(rèn)5000
* @param {string} ping 心跳名稱 默認(rèn)字符串ping
*/
sendPing()巨人的肩膀
以上就是Vue中使用及封裝websocket示例詳解的詳細(xì)內(nèi)容,更多關(guān)于Vue封裝websocket的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
如何在Vue3中使用視頻庫(kù)Video.js實(shí)現(xiàn)視頻播放功能
在Vue3項(xiàng)目中集成Video.js庫(kù),可以創(chuàng)建強(qiáng)大的視頻播放功能,這篇文章主要介紹了如何在Vue3中使用視頻庫(kù)Video.js實(shí)現(xiàn)視頻播放功能,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-09-09
vue 使用 sortable 實(shí)現(xiàn) el-table 拖拽排序功能
這篇文章主要介紹了vue 使用 sortable 實(shí)現(xiàn) el-table 拖拽排序功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
Vue + iView實(shí)現(xiàn)Excel上傳功能的完整代碼
前一段時(shí)間項(xiàng)目經(jīng)歷了前端上傳文件的過(guò)程,首先進(jìn)入頁(yè)面會(huì)展示默認(rèn)的樣子,選中要上傳的excel文件,本文通過(guò)實(shí)例圖文相結(jié)合給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-06-06
Vue3?KeepAlive實(shí)現(xiàn)原理解析
KeepAlive?是一個(gè)內(nèi)置組件,那封裝一個(gè)組件對(duì)于大家來(lái)說(shuō)應(yīng)該不會(huì)有太大的困難,它的核心邏輯在于它的?render?函數(shù),它用?map?去記錄要緩存的組件,就是?[key,vnode]?的形式,這篇文章主要介紹了Vue3?KeepAlive實(shí)現(xiàn)原理,需要的朋友可以參考下2022-09-09
Vue2.0 實(shí)現(xiàn)移動(dòng)端圖片上傳功能
本文主要介紹VUE2.0圖片上傳功能的實(shí)現(xiàn)。原理是通過(guò)js控制和input標(biāo)簽的方式完成這一效果,無(wú)需加載其他組件。具體實(shí)例大家大家參考下本文2018-05-05

