flying-monkey/jsFile/ws.js

59 lines
1.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// 初始化io对象
// import { host } from "@/utils/config.js";
import io from '@hyoga/uni-socket.io';
let mq = [];
let audio = null;
function makeVoice(msg) {
audio = new Audio(msg);
audio.play();
audio.addEventListener("ended", endCall);
}
function endCall() {
if (audio) {
audio.removeEventListener("ended", endCall);
console.log("消息播放完毕");
}
mq.shift();
if (mq.length) {
makeVoice(mq[0]);
}
}
let socket = io('http://7and5.cn' + ":2120");
// uid 其实就是网点ID每个网点的ID是唯一的
// 当socket连接后发送登录请求
socket.on("connect", function () {
console.log("socket连接成功");
mq = [];
const uid = localStorage.getItem("outlets_id");
uid && socket.emit("login", uid);
});
socket.on("connect_error", function (err) {
console.log("socket连接失败,尝试重新连接");
setTimeout(() => {
socket.connect();
}, 1000);
});
socket.on("disconnect", function () {
console.log("socket断开连接,重新连接");
setTimeout(() => {
socket.connect();
}, 1000);
});
// 当服务端推送来消息时触发
socket.on("new_msg", function (msg) {
console.log(msg);
const data = JSON.parse(msg);
const path = host + data.data.path;
mq.push(path);
if (mq.length === 1) {
// 当前队列中存在语音播报,不立即播放,存入语音队列
makeVoice(path);
}
});
export function reconnect() {
socket.disconnect();
}