import Vue from 'vue'
import Vuex from 'vuex'
import baseUrl from '@/Api/baseUrl.js'
const app=getApp();
Vue.use(Vuex)
export default new Vuex.Store({
state: {
socketTask: null,
interval:null,//心跳事件
timeout:120000,
connectNum : 0,//重连次数
//断线重连定时器
timer:null,
isConnect:false, //连接标识 避免重复连接
sucees:null,
eventlist: '',//单聊信息
grouplist:'',//群聊信息
advice:'',//通知
newadvice:0,//订单消息数量
newevent:0//聊天消息数量
},
mutations: {
WEBSOCKET_INIT(state, url) {
uni.getNetworkType({
success: function (result) {
if (result.networkType != 'none') {
if(state.isConnect) return
const wsuri = baseUrl.websocketapi.url;
const _this = this;
// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
state.socketTask = uni.connectSocket({
url: wsuri,
// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
success(data) {
console.log("websocket连接成功");
},
});
// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
state.socketTask.onOpen((res) => {
console.log("WebSocket连接正常打开中...!");
// 注:只有连接正常打开中 ,才能正常收到消息
if(uni.getStorageSync('userinfo')){
let _data={
userId: uni.getStorageSync('userinfo').id,
type:'REGISTER'
}
state.socketTask.send({
data: JSON.stringify(_data),
async success() {
state.isConnect=true;
console.log("消息发送成功");
},
});
}else{
return
}
//开启心跳
// state.interval=setInterval(() => {
// //发送心跳
// var dataxt = {
// 'userId': uni.getStorageSync("userinfo").id, //
// 'type': 'HEARTBEAT'
// }
// state.socketTask.send({
// data: JSON.stringify(dataxt),
// success() {
// console.log("心跳消息发送成功");
// },
// fail(e){
// console.log('心跳发送失败了 ...执行重连');
// state.isConnect=false;
// clearInterval(state.interval);
// state.socketTask.close({})
// _this.dispatch('reConnect');
// }
// });
// }, state.timeout);
state.socketTask.onMessage((res) => {
console.log("收到服务器内容111111:" + res.data);
let datas=res.data;
if(datas.includes('msg')&&!datas.includes('HEARTBEAT')){
//console.log("收到服务器内容:" + JSON.stringify(state.eventlist));
let {id,fromGodId,toGodId,headImg,toGroupId,address,msgType,src,latitude,content,width,name,time,contentType,height,longitude,longTime}=JSON.parse(datas).data
if(contentType=="SINGLE_SENDING"&&msgType<5){
uni.showTabBarRedDot({index:2})
state.eventlist=JSON.parse(datas).data;
plus.sqlite.executeSql({
name: 'first',
sql: `insert into databasedl values('${id}','${fromGodId}','${toGodId}','${toGroupId}','${headImg}','${longTime}','${width}','${height}','${name}','${address}','${latitude}','${longitude}','${content}','${src}','${msgType}','${contentType}','${time}')`,
success: function(e) {
console.log('插入数据成功')
//plus.nativeUI.alert('插入数据成功');
},
fail: function(e) {
console.log('插入数据失败 ')
//plus.nativeUI.alert('插入数据失败');
}
});
}else if(contentType=="GROUP_SENDING"&&msgType<5){
state.grouplist=JSON.parse(datas).data;
console.log(JSON.parse(datas).data)
// plus.sqlite.executeSql({
// name: 'first',
// sql: `insert into databaseql values('${id}','${fromGodId}','${toGodId}','${toGroupId}','${headImg}','${longTime}','${width}','${height}','${name}','${address}','${latitude}','${longitude}','${content}','${src}','${msgType}','${contentType}','${time}')`,
// success: function(e) {
// console.log('插入数据成功')
// //plus.nativeUI.alert('插入数据成功');
// },
// fail: function(e) {
// console.log('插入数据失败 ')
// //plus.nativeUI.alert('插入数据失败');
// }
// });
}else if(contentType=="ADVICE"&&msgType>=5){
console.log("收到服务器通知55555:" + datas);
state.advice=JSON.parse(datas).data;
}
}
});
})
// 监听关闭
state.socketTask.onClose(()=>{
// state.socketTask = null;
//清除定时器
state.isConnect=false;
// clearInterval(state.interval);
//state.interval = null
});
// 监听错误
state.socketTask.onError((e)=>{
//state.socketTask = null;
state.isConnect=false;
// clearInterval(state.interval);
});
uni.onNetworkStatusChange(function (res) {
if(!res.isConnected){
_this.dispatch('reConnect');
}
});
}else{
console.log('网络已断开');
state.isConnect=false;
// 网络断开后显示model
uni.showModal({
title: '网络错误',
content: '请重新打开网络',
showCancel: false,
success: function(res) {
if (res.confirm) {
console.log('用户点击确定')
}
}
})
}
}
});
},
EMPTY(state){
state.newadvice=0;
},
WEBSOCKET_CLOSE(state){
state.isConnect=false;
//clearInterval(state.interval);
console.log('熄灯了111')
state.socketTask.close({})
},
WEBSOCKET_SEND(state, p) {
const that=this;
state.sucees=null;
console.log("ws发送!");
state.socketTask.send({
data: p,
async success() {
state.sucees=true
console.log('发送成功')
},
async fail(e){
console.log('发送失败')
if( state.connectNum>10){
uni.showToast({
title: '聊天服务器不稳定,正在重连...',
icon:'none'
});
}
state.isConnect=false;
state.sucees=false
state.socketTask.close({})
that.dispatch('WEBSOCKET_INIT');
setTimeout(()=>{
that.dispatch('WEBSOCKET_SEND',p);
state.connectNum += 1;
},300)
}
});
},
},
actions: {
EMPTY({
commit
}){
commit('EMPTY')
},
WEBSOCKET_INIT({
commit
}, url) {
commit('WEBSOCKET_INIT', url)
},
WEBSOCKET_CLOSE({
commit,state
}) {
console.log('灯熄灭了')
commit('WEBSOCKET_CLOSE')
},
WEBSOCKET_SEND({
commit,state
}, p) {
commit('WEBSOCKET_SEND', p)
},
reConnect({commit,state}) {
console.log('重连1111')
if (state.connectNum > 5) {
state.socketTask.close({})
state.isConnect=false;
clearInterval(state.interval);
uni.showToast({
title: '聊天服务中断,请重新登录',
icon:'none'
});
uni.reLaunch({
url: '/pages/login/index'
});
state.connectNum += 1;
}else if (state.connectNum > 50) {
state.timer = setTimeout(() => {
commit('WEBSOCKET_INIT')
}, 50000)
state.connectNum += 1;
} else {
console.log('重连')
state.timer = setTimeout(() => {
commit('WEBSOCKET_INIT')
}, 3000)
state.connectNum += 1;
}
},
JYJPUSH_INIT({
commit
}){
commit('JYJPUSH_INIT')
}
}
})
欢迎咨询问题,带前端徒弟小白QQ728045048
2 个评论
要回复文章请先登录或注册
1***@qq.com
jonychen1