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 // 是否主動斷開
? ? this.timeoutNumber = time // 心跳檢測間隔
? ? this.heartbeatTimer = null // 心跳檢測定時器
? ? this.reconnectTimer = null // 斷線重連定時器
? ? this.socketExamples = null // websocket實例
? ? this.againTime = 3 // 重連等待時間(單位秒)
? }
? // 初始化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 開始初始化')
? ? ? // 監(jiān)聽 WebSocket 連接打開事件
? ? ? try {
? ? ? ? this.socketExamples.onOpen(() => {
? ? ? ? ? console.log('WebSocket 連接成功')
? ? ? ? ? this.isConnect = true
? ? ? ? ? clearInterval(this.heartbeatTimer)
? ? ? ? ? clearTimeout(this.reconnectTimer)
? ? ? ? ? // 打開心跳檢測
? ? ? ? ? this.heartbeatCheck()
? ? ? ? })
? ? ? ? // 監(jiān)聽 WebSocket 接受到服務器的消息事件
? ? ? ? this.socketExamples.onMessage((res) => {
? ? ? ? ? console.log('收到消息')
? ? ? ? ? uni.$emit('message', res)
? ? ? ? })
? ? ? ? // 監(jiān)聽 WebSocket 連接關(guān)閉事件
? ? ? ? this.socketExamples.onClose(() => {
? ? ? ? ? console.log('WebSocket 關(guān)閉了')
? ? ? ? ? this.isConnect = false
? ? ? ? ? this.reconnect()
? ? ? ? })
? ? ? ? // 監(jiān)聽 WebSocket 錯誤事件
? ? ? ? this.socketExamples.onError((res) => {
? ? ? ? ? console.log('WebSocket 出錯了')
? ? ? ? ? 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)
? ? ? ? }
? ? ? })
? ? })
? }
? // 開啟心跳檢測
? heartbeatCheck() {
? ? console.log('開啟心跳')
? ? 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)閉的話队橙,進行重連
? ? 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實例未連接
if (!getApp().globalData.socketObj.isConnect) {
? getApp().globalData.socketObj.initSocket()
}
? } else {
// 如果沒有sockt實例华弓,則創(chuàng)建
getApp().globalData.socketObj = new WebSocketClass(
? `wss:這里是地址`,
? 60
)
getApp().globalData.socketObj.initSocket()
? }