talk_appAmin/store/modules/chat.js

123 lines
3.6 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.

import config from "@/config";
import storage from "@/utils/storage";
import constant from "@/utils/constant";
import { login, logout, getInfo } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { GetListid } from "@/api/signln/SignTa/SignTa";
const baseUrl = config.baseUrl;
const qnDomain = config.qnDomain;
const chat = {
state: {
token: getToken(),
socket: storage.get(constant.socket),
sysMessageInfo: storage.get(constant.sysMessageInfo),
activiInfo: storage.get(constant.activiInfo),
sysAuditInfo: storage.get(constant.sysAuditInfo),
userMessageinfo: storage.get(constant.userMessageinfo),
interactMessage: storage.get(constant.interactMessage),
},
mutations: {
SET_socket: (state, socket) => {
state.socket = socket;
storage.set(constant.socket, socket);
},
SET_userMessageinfo: (state, userMessageinfo) => {
state.userMessageinfo = userMessageinfo;
storage.set(constant.userMessageinfo, userMessageinfo);
},
},
actions: {
// 进行webSocket链接
webSockerInfo({ commit, state }) {
GetListid().then((res) => {
let socket = null;
let heartBeatInterval = null;
let reconnectTimeout = null;
const connect = () => {
const fileWithoutProtocol = baseUrl.replace(/^https?:\/\//, "");
const url2 = "ws://" + fileWithoutProtocol + "/text/text?" + res;
socket = uni.connectSocket({
url: url2,
success: () => {
console.log("ws连接成功");
},
});
commit("SET_socket", socket);
socket.onOpen(() => {
console.log("WebSocket连接已打开");
// 开始心跳
startHeartBeat();
resolve();
});
socket.onMessage((event) => {
console.log("收到WebSocket消息", event.data);
const jsonObject = JSON.parse(event.data);
if (jsonObject.messageType == 51 || jsonObject.messageType == 52) {
console.log("聊天新消息111:", jsonObject);
commit("SET_userMessageinfo", jsonObject);
}
});
socket.onError((error) => {
console.error("WebSocket发生错误", error);
reconnect();
});
socket.onClose(() => {
console.log("WebSocket连接已关闭");
reconnect();
});
};
const startHeartBeat = () => {
heartBeatInterval = setInterval(() => {
if (socket && socket.readyState === 1) {
const info = {
fromid: null,
toid: 0,
content: "heartBeat",
};
socket.send({
data: JSON.stringify(info),
success: () => {
console.log("心跳包发送成功");
},
});
}
}, 5000); // 每5秒发送一次心跳包
};
const stopHeartBeat = () => {
if (heartBeatInterval) {
clearInterval(heartBeatInterval);
heartBeatInterval = null;
}
};
const reconnect = () => {
stopHeartBeat();
if (reconnectTimeout) {
clearTimeout(reconnectTimeout);
reconnectTimeout = null;
}
reconnectTimeout = setTimeout(() => {
console.log("尝试重新连接WebSocket");
connect();
}, 5000); // 5秒后重连
};
connect();
});
},
},
};
export default chat;