Newer
Older
urbanLifeline_YanAn / src / utils / ws / useSocket.js
@zhangzhihui zhangzhihui 18 hours ago 1 KB 1
import { ref, watchEffect, watch } from 'vue';
import useWebSocket, { SocketStatus } from './useWebSocket';
// 用户的store,用于检测登录
// import { useAdminStore } from '@stores/adminStore';
import useUserStore from '@/store/modules/user';

import { getToken } from '@/utils/auth';

export default function useSocket(path) {
  // window.location.host
  // '58.51.132.86:8102'
  // 192.168.16.135:13000
  // 192.168.16.254:13002
  // mess_notice
  // ws://server2.wh-nf.cn:8088/prod-api/mess_notice

  let url =
    import.meta.env.VITE_APP_ENV == 'development'
      ? 'ws://192.168.16.135:13002/' + '/mess_notice'
      : 'wss://server2.wh-nf.cn:8088/prod-api/mess_notice';
  // let url =
  //   import.meta.env.VITE_APP_ENV == 'development'
  //     ? 'ws://192.168.16.254:13002/' + '/mess_notice'
  //     : 'ws://' + window.location.host + '/' + path;
  const { status, message, error, connect, disconnect } = useWebSocket({
    url,
    heartBeatData: 'ping',
    token: getToken(),
  });

  const { userInfo } = storeToRefs(useUserStore());
  const chatMessage = ref(null);
  const socketStatusText = ref('');

  window.addEventListener('offline', function () {
    console.log('网络连接已断开');
  });

  window.addEventListener('online', function () {
    console.log('网络连接已恢复');
    // 在网络连接恢复后执行的操作
    retryConnect();
  });

  watch(
    () => status.value,
    newVal => {
      if (newVal != SocketStatus.Connected) {
        socketStatusText.value = newVal;
      }
    }
  );

  watch(
    () => message.value,
    newVal => {
      if (newVal) {
        chatMessage.value = newVal;
      }
    }
  );

  watchEffect(() => {
    // 检测登录后就发起连接,退出后断开连接
    if (userInfo.value.userId) {
      connect();
    } else {
      disconnect();
    }
  });

  const retryConnect = () => {
    if (status.value !== SocketStatus.Connected) {
      connect();
    }
  };

  return {
    socketStatusText,
    chatMessage,
    retryConnect,
  };
}