wo-user-part-uniapp/unisocket/unisocket.js
2020-03-23 19:56:47 +08:00

63 lines
1.8 KiB
JavaScript

const my = {
socket : undefined,
reconnecting: undefined,
listeners: {}
}
module.exports={
initSocket(){
if (!my.socket || my.socket.readyState!==my.socket.OPEN && getApp()._SS.nodeHost) {
console.log('WebSocket connecting...')
my.socket = uni.connectSocket({
url: getApp()._SS.nodeHost.replace(/^http/, 'ws'),
complete: ()=>{}
})
my.socket.onOpen((res)=>{
console.log('WebSocket onOpen: ', res)
clearInterval(my.reconnecting)
delete my.reconnecting
})
my.socket.onClose((res)=>{
console.log('Websocket onClose: ', res)
if (!my.reconnecting)
my.reconnecting = setInterval(()=>{
console.log(new Date(), 'WebSocket reconnecting...')
this.initSocket()
}, 5000) // 每5秒尝试重连
})
my.socket.onError((err)=>{
console.log('Websocket onError: ', err)
})
my.socket.onMessage(({data})=>{ // 在这里统一分发消息
try {
let dataObj = JSON.parse(data)
console.log('WebSocket onMessage for event: ', dataObj.event)
let listeners = my.listeners[dataObj.event] || []
for (let listener of listeners) {
listener(dataObj)
}
}catch(exception){
console.log(new Date(), 'unknown message', data)
return
}
})
}
return my.socket
},
closeSocket(){
my.socket.close()
setTimeout(()=>{
clearInterval(my.reconnecting)
delete my.reconnecting
}, 2000)
},
addListener(event, listener){
if (Array.isArray(my.listeners[event]) && typeof(listener)==='function') {
my.listeners[event].push(listener)
}else {
my.listeners[event]=[listener]
}
return this
}
}