// 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;