Vue中使用及封裝websocket示例詳解
更新時間:2023年07月04日 12:00:42 作者:牛奔
這篇文章主要為大家介紹了Vue中使用及封裝websocket示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jì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ù)但連接未建立時進(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) } // 注冊監(jiān)聽事件 window.addEventListener('onmessageWS', getsocketData) // 在需要的時候卸載監(jiān)聽事件,比如離開頁面 window.removeEventListener('onmessageWS', getsocketData)
API
僅三個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的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
如何在Vue3中使用視頻庫Video.js實現(xiàn)視頻播放功能
在Vue3項目中集成Video.js庫,可以創(chuàng)建強(qiáng)大的視頻播放功能,這篇文章主要介紹了如何在Vue3中使用視頻庫Video.js實現(xiàn)視頻播放功能,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-09-09vue 使用 sortable 實現(xiàn) el-table 拖拽排序功能
這篇文章主要介紹了vue 使用 sortable 實現(xiàn) el-table 拖拽排序功能,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12Vue + iView實現(xiàn)Excel上傳功能的完整代碼
前一段時間項目經(jīng)歷了前端上傳文件的過程,首先進(jìn)入頁面會展示默認(rèn)的樣子,選中要上傳的excel文件,本文通過實例圖文相結(jié)合給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-06-06