111 lines
2.9 KiB
JavaScript
111 lines
2.9 KiB
JavaScript
import {SOCKETAPI1} from "@/common/utils/config.js"
|
||
import store from '@/common/store'
|
||
var socketTask = {}
|
||
function connectSocketInit(state) {
|
||
//保存是否是断开重连的
|
||
store.commit("setPropName", {
|
||
propName: 'socketState',
|
||
value: state
|
||
});
|
||
// 创建一个socketTask对象【发送、接收、关闭socket都由这个对象操作】
|
||
socketTask = uni.connectSocket({
|
||
// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://192.168.31.25:9099【特别容易犯的错误】
|
||
url: SOCKETAPI1+store.state.userInfo.id,
|
||
success(data) {
|
||
//设置是否是手动关闭的
|
||
store.commit("setPropName", {
|
||
propName: 'closeWebSocket',
|
||
value: false
|
||
});
|
||
},
|
||
});
|
||
socketTask.onOpen((res) => {
|
||
console.log("WebSocket连接正常!");
|
||
clearTimeout(store.state.reconnectTimeOut)
|
||
clearTimeout(store.state.heartbeatInterval)
|
||
//socket设置为打开状态
|
||
store.commit("setPropName", {
|
||
propName: 'is_open_socket',
|
||
value: true
|
||
});
|
||
store.commit("start");
|
||
// 注:只有连接正常打开中 ,才能正常收到消息
|
||
socketTask.onMessage((res) => {
|
||
let message = Object.assign({socketState:store.state.socketState},JSON.parse(res.data))
|
||
store.commit('updateSocketMessage', message);
|
||
});
|
||
})
|
||
// 这里仅是事件监听【如果socket关闭了会执行】
|
||
socketTask.onClose(() => {
|
||
console.log("已经被关闭了")
|
||
//设置socket为关闭
|
||
store.commit("setPropName", {
|
||
propName: 'is_open_socket',
|
||
value: false
|
||
});
|
||
if(!store.state.closeWebSocket){
|
||
store.commit("reconnect");
|
||
}
|
||
})
|
||
socketTask.onError(() => {
|
||
console.log("websocket连接异常")
|
||
})
|
||
//将socket存到store中
|
||
store.commit("setPropName", {
|
||
propName: 'socket',
|
||
value: socketTask
|
||
});
|
||
//将socket存到内存中
|
||
uni.setStorageSync("SOCKET", socketTask);
|
||
}
|
||
//开启心跳检测
|
||
// function start(){
|
||
// heartbeatInterval = setTimeout(()=>{
|
||
// console.log("心跳");
|
||
// socketTask.send({
|
||
// data: "请求一次发送一次message",
|
||
// async success() {
|
||
// console.log("消息发送成功");
|
||
// },
|
||
// fail(){
|
||
// console.log("发送失败,重新连接....");
|
||
// }
|
||
// });
|
||
// },3000)
|
||
// }
|
||
//重新连接
|
||
function reconnect(){
|
||
//停止发送心跳
|
||
clearInterval(heartbeatInterval)
|
||
//如果不是人为关闭的话,人为关闭就是在退出的时候,进行重连
|
||
if(!store.state.is_open_socket){
|
||
reconnectTimeOut = setTimeout(()=>{
|
||
socketState = 1;
|
||
connectSocketInit(1);
|
||
},3000)
|
||
}
|
||
}
|
||
// 关闭websocket【离开这个页面的时候执行关闭】
|
||
function closeSocket() {
|
||
return new Promise((resolve, reject) => {
|
||
socketTask.close({
|
||
success(res) {
|
||
is_open_socket = false;
|
||
closeWebSocket = true;
|
||
console.log("关闭成功", res)
|
||
resolve(res)
|
||
},
|
||
fail(err) {
|
||
console.log("关闭失败", err)
|
||
}
|
||
})
|
||
})
|
||
}
|
||
|
||
export {
|
||
socketTask,
|
||
connectSocketInit,
|
||
closeSocket,
|
||
reconnect
|
||
};
|