1.移动端使用socket.io插件来实现数据实时更新的效果
插件文档地址:https://github.com/guyue88/hyoga-uni-socket.io
安装插件:npm i @hyoga/uni-socket.io;
引入使用:
data(){
return {
timer: '',
socketTask: null,
}
},
onShow(){
//后台接口地址
let socketUrl = http.config.baseURL;
// 小程序中必须是 wss:// 协议
let socket = socketUrl.replace("https","wss").replace("http","ws").replace("tianjs/services","");
// 创建客户端链接,连接服务器
this.socketTask = io(socket,{
//注意这里必须加上['websocket']否则项目会报错 (坑点)
autoConnect: true,
transports: ['websocket', 'xhr-polling', 'jsonp-polling'],
reconnect: true,
path: '/socket.io/',
timeout: 300000,
reconnectionDelayMax: 1000,
reconnectionDelay: 500
});
this.openSocket();
this.timer = setInterval(this.openSocket(), 10 * 60 * 1000);
},
watch:{
gateId: function () {
let that = this
setTimeout(function () {
that.openSocket()
}, 1000)
},
},
methods: {
openSocket(){
// 连接服务器成功
this.socketTask.on("connect", () => {
console.log("连接成功...");
let token = localStorage.getItem('token');
let that = this;
setTimeout(function () {
// 发送消息到服务器,事件名为‘userInfo’(事件名跟后端沟通好)
that.socketTask.emit("userInfo", {parkingId: that.parkingId, token: token});
}, 4000);
});
// 监听后端服务器‘newPics’事件名发送的汽车图片(事件名跟后端沟通好)
this.socketTask.on('newPics', (data) => {
if (!data) { return };
if (this.parkingId === 'null' || this.parkingId === null) {
console.log('车场信息加载不全,刷新页面!')
return
};
if (data === '信息添加成功') { return };
// 接收到服务器的数据并处理
if (this.inPassId === data.passageId) {
this.inImg = '';
let file = data.fileUrl.replace('http:', 'https:');
file = file.replace('zwei-prod.obs.cn-north-1.myhuaweicloud.com', 'parking.zweiy.com/gatePicture');
this.inImg = file;
}
if (this.outPassId === data.passageId) {
this.outImg = '';
let file = data.fileUrl.replace('http:', 'https:');
file = file.replace('zwei-prod.obs.cn-north-1.myhuaweicloud.com', 'parking.zweiy.com/gatePicture');
this.outImg = file;
}
});
// 监听后端服务器‘newInfos’事件发送的汽车详情(事件名跟后端沟通好)
this.socketTask.on('newInfos', (data) => {
if (!data) { return };
if (this.parkingId === 'null' || this.parkingId === null) {
console.log('车场信息加载不全,刷新页面!')
return
};
if (data === '信息添加成功') { return };
// 接收到服务器的数据并处理
if (this.inPassId === data.passageId) {
this.inSinData = data;
this.inSinData.newCarNo = this.inSinData.carNo;
//播放声音
// this.dingding(this.inSound)
}
if (this.outPassId === data.passageId) {
this.outSinData = data;
//播放声音
// this.dingding(this.outSound)
}
});
// 连接关闭中
this.socketTask.on("disconnect", () => {
console.log("连接关闭中...");
});
},
},
beforeDestroy(){
clearInterval(this.timer);
},