useSocketStore.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { defineStore } from "pinia";
  2. import { store } from "@/stores/store";
  3. import main from "../main";
  4. import type { SocketStore } from "./type";
  5. export const useSocketStore = defineStore({
  6. id: "socket",
  7. state: (): SocketStore => ({
  8. // 連接狀態
  9. isConnected: false,
  10. // 訊息內容
  11. message: "",
  12. // 重新連接錯誤
  13. reconnectError: false,
  14. // 心跳消息發送時間
  15. heartBeatInterval: 50000,
  16. // 心跳定時器
  17. heartBeatTimer: 0
  18. }),
  19. actions: {
  20. // 開啟連接
  21. SOCKET_ONOPEN(event: any) {
  22. console.log("successful websocket connection");
  23. console.log('event',event);
  24. main.config.globalProperties.$socket = event.currentTarget;
  25. this.isConnected = true;
  26. // 連接成功時啟動定時發送心跳訊息,避免被服務器斷開連接
  27. this.heartBeatTimer = window.setInterval(() => {
  28. const message = "心跳消息";
  29. this.isConnected &&
  30. main.config.globalProperties.$socket.sendObj({
  31. code: 200,
  32. msg: message
  33. });
  34. }, this.heartBeatInterval);
  35. },
  36. // 關閉連接
  37. SOCKET_ONCLOSE(event: any) {
  38. this.isConnected = false;
  39. // 連接關閉時停掉心跳訊息
  40. window.clearInterval(this.heartBeatTimer);
  41. this.heartBeatTimer = 0;
  42. console.log("連接已斷線:" + new Date());
  43. console.log(event);
  44. },
  45. // 發生錯誤
  46. SOCKET_ONERROR(event: any) {
  47. console.error(event);
  48. },
  49. // 收到服務端發送的訊息
  50. SOCKET_ONMESSAGE(message: any) {
  51. this.message = message;
  52. console.log('SOCKET_ONMESSAGE',message);
  53. },
  54. // 自動重連
  55. SOCKET_RECONNECT(count: any) {
  56. console.info("重新連接中...", count);
  57. },
  58. // 重連錯誤
  59. SOCKET_RECONNECT_ERROR() {
  60. this.reconnectError = true;
  61. }
  62. }
  63. });
  64. // Need to be used outside the setup
  65. export function useSocketStoreWithOut() {
  66. return useSocketStore(store);
  67. }