微信小程序中連接socket
onLoad: function (options) {
/* 初始化連接 */
console.log('開始連接')
// websocket連接
wx.connectSocket({
url: url,
header: {
'content-type': 'application/json'
},
method: 'post',
success: res => {
console.log('連接成功', res)
// 設(shè)置連接狀態(tài)
this.connectStatus = 1
// 心跳
clearInterval(this.heartListen)
this.heartListen = setInterval(() => {
if (this.connectStatus === 0) {
console.log('監(jiān)聽到?jīng)]心跳了,搶救一下')
clearInterval(this.heartListen)
this.reconnect()
} else {
// console.log('我還活著')
}
}, 3000)
},
fail: err => {
console.error('連接失敗')
}
})
// 監(jiān)聽webSocket錯(cuò)誤
wx.onSocketError(res => {
console.log('監(jiān)聽到 WebSocket 打開錯(cuò)誤歼冰,請(qǐng)檢查冕香!')
// 修改連接狀態(tài)
this.connectStatus = 0
})
// 監(jiān)聽WebSocket關(guān)閉
wx.onSocketClose(res => {
console.log('監(jiān)聽到 WebSocket 已關(guān)閉淌铐!')
this.connectStatus = 0
})
// websocket打開
wx.onSocketOpen(res => {
console.log('監(jiān)聽到 WebSocket 連接已打開!')
})
// 收到websocket消息
wx.onSocketMessage(res => {
this.getSocketMsg(JSON.parse(res.data)) // 收到的消息為字符串橙依,需處理一下
})
}
/* 重連 */
reconnect() {
console.log('嘗試重連')
wx.closeSocket() // 重連之前手動(dòng)關(guān)閉一次
this.connectSocket()
}
/* 關(guān)閉websocket */
closeSocket(removeChat) {
wx.closeSocket({
success: res => {
// code
}
})
}
/* 添加watcher */
addWatcher (fn) {
this.watcherList.push(fn)
return this.watcherList.length - 1 // 返回添加位置的下標(biāo),Page unload的時(shí)候方便刪除List成員
}
/* 刪除watcher */
delWatcher (index) {
this.watcherList.splice(index, 1)
// console.log('銷毀watcher', this.watcherList)
}
}
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面卸載
*/
onUnload: function () {
// 銷毀
wx.closeSocket({
success: res => {
// code
}
})
}