微信小程序中连接socket
onLoad: function (options) {
/* 初始化连接 */
console.log('开始连接')
// websocket连接
wx.connectSocket({
url: url,
header: {
'content-type': 'application/json'
},
method: 'post',
success: res => {
console.log('连接成功', res)
// 设置连接状态
this.connectStatus = 1
// 心跳
clearInterval(this.heartListen)
this.heartListen = setInterval(() => {
if (this.connectStatus === 0) {
console.log('监听到没心跳了,抢救一下')
clearInterval(this.heartListen)
this.reconnect()
} else {
// console.log('我还活着')
}
}, 3000)
},
fail: err => {
console.error('连接失败')
}
})
// 监听webSocket错误
wx.onSocketError(res => {
console.log('监听到 WebSocket 打开错误,请检查!')
// 修改连接状态
this.connectStatus = 0
})
// 监听WebSocket关闭
wx.onSocketClose(res => {
console.log('监听到 WebSocket 已关闭!')
this.connectStatus = 0
})
// websocket打开
wx.onSocketOpen(res => {
console.log('监听到 WebSocket 连接已打开!')
})
// 收到websocket消息
wx.onSocketMessage(res => {
this.getSocketMsg(JSON.parse(res.data)) // 收到的消息为字符串,需处理一下
})
}
/* 重连 */
reconnect() {
console.log('尝试重连')
wx.closeSocket() // 重连之前手动关闭一次
this.connectSocket()
}
/* 关闭websocket */
closeSocket(removeChat) {
wx.closeSocket({
success: res => {
// code
}
})
}
/* 添加watcher */
addWatcher (fn) {
this.watcherList.push(fn)
return this.watcherList.length - 1 // 返回添加位置的下标,Page unload的时候方便删除List成员
}
/* 删除watcher */
delWatcher (index) {
this.watcherList.splice(index, 1)
// console.log('销毁watcher', this.watcherList)
}
}
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
// 销毁
wx.closeSocket({
success: res => {
// code
}
})
}