基本
带自动重连,自动心跳发送
使用情况
// import $store from '../index.js'
// import vueconfig from '../../vue.config.js'
import Wst from './lid/websocketL.js'
import WxStorage from "../static/lib/wxStorage.js" //微信Storage
// var url = 'ws://' + vueconfig.devServer.proxy["/cloud"].target.substring(5) + '/websocket';
import $store from './index.js'
import apis from "./apiConfig.js"
// let url = 'ws://192.168.0.108:9034/websocket';
// let url = 'ws://223.82.109.183:2082/websocket';
let url = apis.wsapi;
const webSockets = new Wst(url);
let websocket = {
state: {
webSockets: webSockets, //websocket实例
socket: '', //websoclet主体
socketValue: '', //接收的数据
socketState: false, // 当前连接websocket状态
socketInterval: false, //心跳
socketTimeout: false, //检测服务器是否连接成功timeout
socketInterTime: 5000, //心跳时间 秒*1000
socketStateMY: true, //总控 在退出登入时,强行关闭心跳
},
actions: {
connectws({
state,
commit
}) {
console.log("开启websocket")
var getValue = function(res) { // 消息回调
commit("setSocketValue", res);
}
var getState = function(res) { // 状态回调
commit("setState", res);
}
var getws = function(res) { // 主体回调
commit("setSocket", res);
}
// console.log(webSockets.$callBack)
// let equipmentInformation = navigator.userAgent;
// var Data = {
// router: "share",
// res: {
// ...$store.state.logs.user,
// equipmentInformation: equipmentInformation
// },
// }
var ws = webSockets.$callBack(getValue, getState, getws, state.puserID || WxStorage.get("ids"))
.$connect();
},
},
mutations: {
wsOut(state, value) {
webSockets.$outws();
},
setSocket(state, value) { //websocket主体
state.socket = value;
},
setSocketValue(state, value) {
console.log(value, 222222222222)
// if (value.router) { //正常数据返回
// //去除心跳数据
// if (value.router == 'share/heartbeat') {
// return;
// }
console.log(value)
state.socketValue = value;
// console.log(value, 'websocket信息')
// } else { //异常数据返回
// console.log(value, '异常')
// }
},
//本地建造数据传递
setMyvalue(state, value) {
state.socketValue = value;
},
setsocketStateMY(state, value) {
state.socketStateMY = value;
},
setState(state, value) {
state.socketState = value;
},
}
}
export default websocket
源码
// uniapp版本websocket总控制
function Wst(url) {
this.url = url || "";
this.ws = "";
this.ourControl = true; //总控
this.state = false;
this.timeIntval = false;
this.timeIntvalTime = 5000;
this.WebSocketValue = "";
this.backValue = function(res) {
console.log(res, "未设置msg返回函数");
};
this.getws = "";
this.Data = "";
this.heartBeat = "";
this.loginData = "";
this.ids = '';
return this;
}
Wst.prototype.$callBack = function(getValue, getState, getws, ids) {
// console.log("设置回调函数")
this.backValue = function(res) {
if (!getValue && !getState) {
console.log(res, "未设置msg返回函数");
} else {
if (getValue) {
getValue(res);
}
if (getState) {
getState(this.state);
}
}
};
this.getws = getws;
this.ids = ids;
return this;
};
Wst.prototype.$connect = function(Data) {
// console.log("开启")
this.ourControl = true;
let that = this;
this.Data = Data;
this.loginData = {
id: this.ids,
type: 'login'
};
this.heartBeat = 'ping';
this.ws = uni.connectSocket({
url: that.url,
success(data) {
console.log(data, "websocket连接成功");
},
});
// console.log(that.url)
this.ws.onOpen((res) => {
// 注:只有连接正常打开中 ,才能正常成功发送消息
// console.log("发送登入消息 websocket")
// console.log(that.loginData)
that.ws.send({
data: JSON.stringify(that.loginData),
async success(res) {
// console.log(res, "登入成功"); //设置登入成功状态 并开启心跳
that.state = true;
that.$heartbeat();
},
});
// 注:只有连接正常打开中 ,才能正常收到消息
that.ws.onMessage((res) => {
// console.log("收到服务器内容:", JSON.parse(res.data));
let d = res.data;
try {
d = JSON.parse(res.data);
} catch (e) {}
that.WebSocketValue = d;
// that.state = true;
// this.$heartbeat();
that.backValue(d);
});
});
// this.ws.onClose((e) => {
// console.log(11111111111111111)
// that.state = false;
// that.backValue(e);
// });
// this.$heartbeat();
this.getws(this.ws);
return this;
};
Wst.prototype.$heartbeat = function() {
let that = this;
let open = function() {
// console.log('开启心跳');
that.ws.send({
data: that.heartBeat,
});
};
let rel = function() {
console.log('重新连接');
that.$connect(that.Data);
};
if (that.timeIntval) {
clearInterval(that.timeIntval);
}
that.timeIntval = setInterval(() => {
if (!this.ourControl) {
return;
}
// console.log(that.state)
if (that.state) {
open();
} else {
rel();
}
}, that.timeIntvalTime);
};
Wst.prototype.$outws = function() {
this.ourControl = false;
clearInterval(this.timeIntval);
this.timeIntval = false;
this.WebSocketValue = {};
this.state = false;
// this.backValue({});
};
export default Wst;