first commit
This commit is contained in:
88
utils/sok.js
Normal file
88
utils/sok.js
Normal file
@@ -0,0 +1,88 @@
|
||||
export const init = () => {
|
||||
var timeout = 30000;
|
||||
var timeoutObj = null;
|
||||
openConnection()
|
||||
|
||||
function checkOpenSocket() {
|
||||
const token = uni.getStorageSync('userInfo');
|
||||
var login = `{"uid":"${token.uid}","send_type":"login"}`
|
||||
uni.sendSocketMessage({
|
||||
data: login,
|
||||
success: res => {
|
||||
return;
|
||||
},
|
||||
fail: err => {
|
||||
// 未连接打开websocket连接
|
||||
openConnection();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function openConnection() {
|
||||
// 打开连接
|
||||
// uni.closeSocket(); // 确保已经关闭后再重新打开
|
||||
uni.connectSocket({
|
||||
url: `ws://192.168.1.63:1017/ws/deviceUpMessage?token=${uni.getStorageSync('token')}`,
|
||||
success(res) {
|
||||
console.log('连接成功 connectSocket=', res);
|
||||
},
|
||||
fail(err) {
|
||||
console.log('连接失败 connectSocket=', err);
|
||||
}
|
||||
});
|
||||
uni.onSocketOpen(res => {
|
||||
console.log('连接成功');
|
||||
});
|
||||
uni.onSocketError(err => {
|
||||
console.log('连接失败');
|
||||
});
|
||||
|
||||
onSocketMessage(); // 打开成功监听服务器返回的消息
|
||||
}
|
||||
// 打开成功监听服务器返回的消息
|
||||
function onSocketMessage() {
|
||||
// 消息
|
||||
timeout = 30000;
|
||||
timeoutObj = null;
|
||||
uni.onSocketMessage(res => {
|
||||
getSocketMsg(res.data); // 监听到有新服务器消息
|
||||
});
|
||||
}
|
||||
// 监听到有新服器消息
|
||||
function getSocketMsg(reData) {
|
||||
console.log(reData);
|
||||
// 监听到服务器消息
|
||||
// console.log('收到服务器消息', reData);
|
||||
reData = JSON.parse(reData);
|
||||
console.log(reData);
|
||||
// if (!reData.type) {
|
||||
// store.commit('setMusicCol', reData)
|
||||
// PhoneState(reData.phone)
|
||||
// // callPhone(res.data.phone)
|
||||
// }
|
||||
// reset(); // 检测心跳reset,防止长时间连接导致连接关闭
|
||||
}
|
||||
// 检测心跳reset
|
||||
function reset() {
|
||||
clearInterval(timeoutObj);
|
||||
start(); // 启动心跳
|
||||
}
|
||||
// 启动心跳 start
|
||||
function start() {
|
||||
console.log(timeout);
|
||||
timeoutObj = setInterval(function() {
|
||||
const token = uni.getStorageSync('userInfo');
|
||||
var login = `{"uid":"${token.uid}","send_type":"login"}`
|
||||
uni.sendSocketMessage({
|
||||
data: login,
|
||||
success: res => {
|
||||
console.log('连接中....,');
|
||||
},
|
||||
fail: err => {
|
||||
console.log('连接失败重新连接....');
|
||||
openConnection();
|
||||
}
|
||||
});
|
||||
}, timeout);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user