放在 methods 里面
initScokets() {
let that = this;
const token = wx.getStorageSync('token')
uni.connectSocket({
url: `ws://101.35.21.148?token=${token}`,
success(res) {
that.open();
that.scoketMessage();
that.TimeOut();
},
fail(err) {
console.log("WebSocket连接失败 connectSocket=", err);
that.error();
},
});
uni.onSocketClose(function(res) {
console.log('WebSocket 已关闭!669');
});
},
open() {
let that = this;
uni.onSocketOpen((res) => {
console.log("WebSocket连接成功....");
that.reset();
});
},
scoketMessage() {
let that = this;
uni.onSocketMessage(function(res) {
console.log("收到服务器内容:" + res.data);
console.log('我是测试号',JSON.parse(res.data).data.msg);
that.serveTime = new Date().getTime();
});
},
TimeOut() {
let that = this;
setInterval(function() {
let times = new Date().getTime();
if (times - that.serveTime > 2000) {
}
}, 500);
},
error() {
let that = this;
console.log(333);
uni.onSocketError(function(res) {
console.log("WebSocket连接打开失败,请检查!");
that.initScokets();
});
},
reset() {
let that = this;
clearInterval(that.timeoutObj);
that.timeoutObj = setInterval(function() {
uni.sendSocketMessage({
data: `PING`,
success: (res) => {
console.log('心跳维持');
},
fail: (err) => {
console.log("心跳维持失败,重新连接....");
that.initScokets();
},
});
}, this.timeout);
},
startSend() {
let that = this
let params={
project_association_id:3,
data:{
msg:'你好(我是测试数据)'
}
}
uni.sendSocketMessage({
data: JSON.stringify(params),
success: (res) => {
console.log('发送');
},
fail: (err) => {
console.log("发送失败,重新连接....");
},
});
},
关闭 Socke
onUnload() {
console.log('隐藏')
clearInterval(this.timeoutObj);
uni.closeSocket();
},