websocket.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { getToken } from '@/utils/auth';
  2. import { ElNotification } from 'element-plus';
  3. import useNoticeStore from '@/store/modules/notice';
  4. // 初始化socket
  5. export const initWebSocket = (url: any) => {
  6. if (import.meta.env.VITE_APP_WEBSOCKET === 'false') {
  7. return;
  8. }
  9. url = url + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID
  10. useWebSocket(url, {
  11. autoReconnect: {
  12. // 重连最大次数
  13. retries: 3,
  14. // 重连间隔
  15. delay: 1000,
  16. onFailed() {
  17. console.log('websocket重连失败');
  18. },
  19. },
  20. heartbeat: {
  21. message: JSON.stringify({type: 'ping'}),
  22. // 发送心跳的间隔
  23. interval: 10000,
  24. // 接收到心跳response的超时时间
  25. pongTimeout: 2000,
  26. },
  27. onConnected() {
  28. console.log('websocket已经连接');
  29. },
  30. onDisconnected() {
  31. console.log('websocket已经断开');
  32. },
  33. onMessage: (_, e) => {
  34. if (e.data.indexOf('ping') > 0) {
  35. return;
  36. }
  37. useNoticeStore().addNotice({
  38. message: e.data,
  39. read: false,
  40. time: new Date().toLocaleString()
  41. });
  42. ElNotification({
  43. title: '消息',
  44. message: e.data,
  45. type: 'success',
  46. duration: 3000
  47. });
  48. }
  49. });
  50. };