import {UserManager} from "@/utils/userManager.js";
class webSocketClass {
constructor(url="ws://127.0.0.1:8088/",time=3) {
this.url = url
this.filterMessagesList = [""]; //服務端返回的內容 message事件不監聽的內容,不會再message返回
this.data = null
this.heartbeatCheckData = {} //心跳發送的內容
this.isCreate = false // WebSocket 是否創建成功
this.isConnect = false // 是否已經連接
this.isInitiative = false // 是否主動斷開
this.timeoutNumber = time // 心跳檢測間隔
this.heartbeatTimer = null // 心跳檢測定時器
this.reconnectTimer = null // 斷線重連定時器
this.socketExamples = null // websocket實例
this.againTime = 3 // 重連等待時間(單位秒)
}
// 初始化websocket連接
initSocket(gameId) {
const _this = this
this.socketExamples = uni.connectSocket({
url: `${_this.url}?gameId=${gameId}&$userId=${UserManager.shared().userInfo.userId}`,
header: {
'content-type': 'application/json',
token: UserManager.shared().userInfo ? UserManager.shared().userInfo.token : ''
},
success: (res) => {
_this.isCreate = true
console.log(res)
},
fail: (rej) => {
console.error(rej)
_this.isCreate = false
}
})
this.createSocket()
}
// 創建websocket連接
createSocket() {
var _this = this
if (this.isCreate) {
console.log('WebSocket 開始初始化')
// 監聽 WebSocket 連接打開事件
try {
this.socketExamples.onOpen(() => {
console.log('WebSocket 連接成功')
this.isConnect = true
clearInterval(this.heartbeatTimer)
clearTimeout(this.reconnectTimer)
// 打開心跳檢測
this.heartbeatCheck()
})
// 監聽 WebSocket 接受到服務器的消息事件
this.socketExamples.onMessage((res) => {
console.log('收到消息---',res.data)
if (_this.filterMessagesList.includes(res.data)) {
console.log(`信息:${res.data}--在過濾列表中不進行推送`)
}else{
uni.$emit('message', res)
}
})
// 監聽 WebSocket 連接關閉事件
this.socketExamples.onClose(() => {
console.log('WebSocket 關閉了')
this.isConnect = false
this.reconnect()
})
// 監聽 WebSocket 錯誤事件
this.socketExamples.onError((res) => {
console.log('WebSocket 出錯了')
console.log(res)
this.isInitiative = false
})
} catch (error) {
console.warn(error)
}
} else {
console.warn('WebSocket 初始化失敗!')
}
}
//判斷是否爲{}
isEmptyObject(value) {
return typeof value === 'object' && Object.keys(value).length === 0;
}
// 發送消息
sendMsg(value) {
if (!this.isEmptyObject(value)){
value["userId"] = UserManager.shared().userInfo ? UserManager.shared().userInfo.userId : ''
}
const param = JSON.stringify(value)
return new Promise((resolve, reject) => {
this.socketExamples.send({
data: param,
success() {
console.log('消息發送成功')
resolve(true)
},
fail(error) {
console.log('消息發送失敗')
reject(error)
}
})
})
}
// 開啓心跳檢測
heartbeatCheck() {
var _this = this
console.log('開啓心跳')
this.heartbeatTimer = setInterval(() => {
_this.sendMsg(_this.heartbeatCheckData)
}, _this.timeoutNumber * 1000)
}
// 重新連接
reconnect() {
// 停止發送心跳
clearTimeout(this.reconnectTimer)
clearInterval(this.heartbeatTimer)
// 如果不是人爲關閉的話,進行重連
if (!this.isInitiative) {
this.reconnectTimer = setTimeout(() => {
this.initSocket()
}, this.againTime * 1000)
}
}
// 關閉 WebSocket 連接
closeSocket(reason = '關閉') {
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('關閉 WebSocket 成功')
},
fail(error) {
console.log('關閉 WebSocket 失敗',error)
}
})
}
}
export {webSocketClass}
js實現websocket
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.