uniapp-websocket的封裝

1.新建webSocket.js

class webSocketClass {

? constructor(url, time) {

? ? this.url = url

? ? this.data = null

? ? this.isCreate = false // WebSocket 是否創(chuàng)建成功

? ? this.isConnect = false // 是否已經(jīng)連接

? ? this.isInitiative = false // 是否主動(dòng)斷開(kāi)

? ? this.timeoutNumber = time // 心跳檢測(cè)間隔

? ? this.heartbeatTimer = null // 心跳檢測(cè)定時(shí)器

? ? this.reconnectTimer = null // 斷線重連定時(shí)器

? ? this.socketExamples = null // websocket實(shí)例

? ? this.againTime = 3 // 重連等待時(shí)間(單位秒)

? }

? // 初始化websocket連接

? initSocket() {

? ? const _this = this

? ? this.socketExamples = uni.connectSocket({

? ? ? url: _this.url,

? ? ? header: {

? ? ? ? 'content-type': 'application/json'

? ? ? },

? ? ? success: (res) => {

? ? ? ? _this.isCreate = true

? ? ? ? console.log(res)

? ? ? },

? ? ? fail: (rej) => {

? ? ? ? console.error(rej)

? ? ? ? _this.isCreate = false

? ? ? }

? ? })

? ? this.createSocket()

? }

? // 創(chuàng)建websocket連接

? createSocket() {

? ? if (this.isCreate) {

? ? ? console.log('WebSocket 開(kāi)始初始化')

? ? ? // 監(jiān)聽(tīng) WebSocket 連接打開(kāi)事件

? ? ? try {

? ? ? ? this.socketExamples.onOpen(() => {

? ? ? ? ? console.log('WebSocket 連接成功')

? ? ? ? ? this.isConnect = true

? ? ? ? ? clearInterval(this.heartbeatTimer)

? ? ? ? ? clearTimeout(this.reconnectTimer)

? ? ? ? ? // 打開(kāi)心跳檢測(cè)

? ? ? ? ? this.heartbeatCheck()

? ? ? ? })

? ? ? ? // 監(jiān)聽(tīng) WebSocket 接受到服務(wù)器的消息事件

? ? ? ? this.socketExamples.onMessage((res) => {

? ? ? ? ? console.log('收到消息')

? ? ? ? ? uni.$emit('message', res)

? ? ? ? })

? ? ? ? // 監(jiān)聽(tīng) WebSocket 連接關(guān)閉事件

? ? ? ? this.socketExamples.onClose(() => {

? ? ? ? ? console.log('WebSocket 關(guān)閉了')

? ? ? ? ? this.isConnect = false

? ? ? ? ? this.reconnect()

? ? ? ? })

? ? ? ? // 監(jiān)聽(tīng) WebSocket 錯(cuò)誤事件

? ? ? ? this.socketExamples.onError((res) => {

? ? ? ? ? console.log('WebSocket 出錯(cuò)了')

? ? ? ? ? console.log(res)

? ? ? ? ? this.isInitiative = false

? ? ? ? })

? ? ? } catch (error) {

? ? ? ? console.warn(error)

? ? ? }

? ? } else {

? ? ? console.warn('WebSocket 初始化失敗!')

? ? }

? }

? // 發(fā)送消息

? sendMsg(value) {

? ? const param = JSON.stringify(value)

? ? return new Promise((resolve, reject) => {

? ? ? this.socketExamples.send({

? ? ? ? data: param,

? ? ? ? success() {

? ? ? ? ? console.log('消息發(fā)送成功')

? ? ? ? ? resolve(true)

? ? ? ? },

? ? ? ? fail(error) {

? ? ? ? ? console.log('消息發(fā)送失敗')

? ? ? ? ? reject(error)

? ? ? ? }

? ? ? })

? ? })

? }

? // 開(kāi)啟心跳檢測(cè)

? heartbeatCheck() {

? ? console.log('開(kāi)啟心跳')

? ? this.data = { state: 1, method: 'heartbeat' }

? ? this.heartbeatTimer = setInterval(() => {

? ? ? this.sendMsg(this.data)

? ? }, this.timeoutNumber * 1000)

? }

? // 重新連接

? reconnect() {

? ? // 停止發(fā)送心跳

? ? clearTimeout(this.reconnectTimer)

? ? clearInterval(this.heartbeatTimer)

? ? // 如果不是人為關(guān)閉的話,進(jìn)行重連

? ? if (!this.isInitiative) {

? ? ? this.reconnectTimer = setTimeout(() => {

? ? ? ? this.initSocket()

? ? ? }, this.againTime * 1000)

? ? }

? }

? // 關(guān)閉 WebSocket 連接

? closeSocket(reason = '關(guān)閉') {

? ? const _this = this

? ? this.socketExamples.close({

? ? ? reason,

? ? ? success() {

? ? ? ? _this.data = null

? ? ? ? _this.isCreate = false

? ? ? ? _this.isConnect = false

? ? ? ? _this.isInitiative = true

? ? ? ? _this.socketExamples = null

? ? ? ? clearInterval(_this.heartbeatTimer)

? ? ? ? clearTimeout(_this.reconnectTimer)

? ? ? ? console.log('關(guān)閉 WebSocket 成功')

? ? ? },

? ? ? fail() {

? ? ? ? console.log('關(guān)閉 WebSocket 失敗')

? ? ? }

? ? })

? }

}

export default webSocketClass


2.在App.vue的globalData添加===》socketObj:null

3.引用?import WebSocketClass from '../../common/webSocket'

4.使用

? ? onLoad(){uni.$on('message', this.getMessage)},

onUnload() {

? uni.$off('message', this.getMessage)

},

methods:{getMessage(msg) {}

console.log(msg)

},

在需要使用的地方使用?

if (getApp().globalData.socketObj) {

// 如果sockt實(shí)例未連接

if (!getApp().globalData.socketObj.isConnect) {

? getApp().globalData.socketObj.initSocket()

}

? } else {

// 如果沒(méi)有sockt實(shí)例,則創(chuàng)建

getApp().globalData.socketObj = new WebSocketClass(

? `wss:這里是地址`,

? 60

)

getApp().globalData.socketObj.initSocket()

? }

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容