12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- import {getWssApiUrl} from "@/config/envApi";
- import {getStorage} from "@/utils/storage";
- import {getObjVal, getObjValue, isString} from "js-fast-way";
- import {useAppStore} from "@/store";
- import {isNullES} from "js-fast-way";
- export default class HcSocket {
- static socketTask = null
- static timeID = null
- static isConnect = false
- static initSocket() {
- let _this = this;
- this.timeID = setInterval(() => {
- if (!_this.isConnect) {
- const { user_id } = getObjValue(getStorage('userInfo'))
- if (isNullES(user_id)) return false;
- _this.connectSocket(user_id)
- } else {
- clearInterval(_this.timeID)
- }
- }, 3000)
- }
- static connectSocket(user_id) {
- const _this = this, store = useAppStore();
- this.socketTask = uni.connectSocket({
- url: getWssApiUrl() + user_id,
- success: ()=> {
- console.log('socket 连接成功')
- },
- fail: () => {
- console.log('socket 连接失败')
- }
- });
- //连接已打开
- this.socketTask.onOpen(function(res) {
- console.log('socket 连接已打开');
- _this.isConnect = true
- const projectId = getStorage('projectId')
- const contractId = getStorage('contractId')
- _this.sendSocketMsg(`${projectId},${contractId}`)
- })
- //连接失败
- this.socketTask.onError(function(res) {
- console.log('socket 连接打开失败,请检查!');
- })
- //监听连接关闭
- this.socketTask.onClose((e) => {
- console.log('socket 连接关闭!');
- //进入重新连接
- setTimeout(() => {
- _this.connectSocket();
- }, 3000)
- })
- //收到的消息
- this.socketTask.onMessage(function({data}) {
- const countData = isString(data) ? JSON.parse(data) : {}
- if (getObjVal(countData)) {
- console.log('收到服务器内容:', countData);
- store.setMsgCountData(countData)
- }
- });
- }
- //发送消息
- static sendSocketMsg(msg) {
- this.socketTask.send({data: msg});
- }
- }
|