websocket.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { useUserStore } from "@/pinia/user-store";
  2. import env from "@/utils/setting";
  3. import { useCySocket } from "@/utils/useCySocket";
  4. import { UseWebSocketReturn } from "@vueuse/core";
  5. let webSocket: UseWebSocketReturn<any> | null = null;
  6. let globalCallback = new Map();
  7. export function closeWebSocket() {
  8. if (webSocket !== null) {
  9. webSocket.close();
  10. webSocket = null;
  11. }
  12. }
  13. export function setCallback(messageName, callback) {
  14. globalCallback.set(messageName, callback);
  15. }
  16. export function sendAMessage(name, data) {
  17. if (globalCallback.has(name)) {
  18. try {
  19. globalCallback.get(name)(data);
  20. } catch {}
  21. }
  22. }
  23. export const socketErrDialog = ref(false);
  24. export function initWebSocket() {
  25. const userStore = useUserStore().userInfo;
  26. const url = `${env.VITE_SOCKET_V2}/intergrationPlatform/${userStore.code}`;
  27. // const url = `${env.VITE_SOCKET_URL}/02896-172.16.30.66-a4f2eddf9e114c7dad5a9473a3d75020fAhr5UY4`;
  28. webSocket = useCySocket(url, {
  29. setInfo: false,
  30. heartbeat: {
  31. pongTimeout: 1000,
  32. message: "heart-beat",
  33. interval: 1000 * 60,
  34. },
  35. onMessage: (ws, e) => {
  36. const data = JSON.parse(e.data);
  37. sendAMessage(data.name || data.code, data.message);
  38. },
  39. });
  40. }
  41. export function sendMeg(code: string, data = null) {
  42. webSocket &&
  43. webSocket.send(
  44. JSON.stringify({
  45. code,
  46. data,
  47. })
  48. );
  49. }