signalR.ts 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. // 官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/signalr/javascript-client?view=aspnetcore-6.0&viewFallbackFrom=aspnetcore-2.2&tabs=visual-studio
  2. import * as signalR from '@microsoft/signalr';
  3. import { ElNotification } from 'element-plus';
  4. import {Cookie} from '/@/utils/storage';
  5. export default {
  6. // signalR对象
  7. SR: null as any,
  8. // 失败连接重试次数
  9. failNum: 4,
  10. baseUrl: import.meta.env.VITE_API_SOCKET_URL,
  11. groupName:'',
  12. init() {
  13. const token = Cookie.get('token');
  14. const connection = new signalR.HubConnectionBuilder()
  15. .withUrl(this.baseUrl, { accessTokenFactory: () => token, skipNegotiation: true, transport: 1 })
  16. .withAutomaticReconnect() //自动重新连接
  17. .configureLogging(signalR.LogLevel.Warning)
  18. .build();
  19. this.SR = connection;
  20. // 断线重连
  21. connection.onclose(async () => {
  22. console.log('当前链接状态:', connection.state);
  23. // 建议用户重新刷新浏览器
  24. await this.start();
  25. });
  26. connection.onreconnected(() => {
  27. console.log('断线重连成功');
  28. /*ElNotification({
  29. type: 'success',
  30. title: '提示',
  31. message: `断线重连成功`,
  32. });*/
  33. });
  34. },
  35. /**
  36. * @description 调用 this.signalR.start().then(async () => { await this.SR.invoke("method")})
  37. * state Connected 已连接 Connecting 正在连接 Disconnected 断开连接 Reconnecting 正在重新连接
  38. * @returns
  39. */
  40. async start() {
  41. try {
  42. //使用async和await 或 promise的then 和catch 处理来自服务端的异常
  43. await this.SR.start();
  44. console.log('当前链接状态:', this.SR.state);
  45. return Promise.resolve();
  46. } catch (error: any) {
  47. this.failNum--;
  48. if (this.failNum > 0 && this.SR.state === 'Disconnected') {
  49. //断开链接重新链接
  50. /*ElNotification({
  51. type: 'warning',
  52. title: '提示',
  53. message: `断开连接了,正在重连, 剩余自动重连次数${this.failNum} 次,如未重连成功,请刷新浏览器重试`,
  54. });*/
  55. setTimeout(async () => {
  56. await this.SR.start();
  57. }, 5000);
  58. }
  59. return Promise.reject(error);
  60. }
  61. },
  62. /**
  63. * @description 加入分组
  64. * @param groupName string 分组名称
  65. * @params {string} CallCenter 呼叫中心
  66. * @params BigScreenDataShow 大屏数据展示
  67. * @returns
  68. */
  69. async joinGroup(groupName: string) {
  70. if (this.SR.state === 'Connected') {
  71. // 判断是否已经建立链接 如果没有 先链接
  72. await this.SR.invoke('JoinGroupAsync', {GroupName:groupName});
  73. } else {
  74. await this.start().then(async () => {
  75. setTimeout(async () => {
  76. await this.SR.invoke('JoinGroupAsync', {GroupName:groupName});
  77. },500)
  78. }).catch((err) => {
  79. console.log(err);
  80. })
  81. }
  82. },
  83. /**
  84. * @description 离开分组
  85. * @param groupName string
  86. * @params CallCenter 呼叫中心
  87. * @params BigScreenDataShow 大屏数据展示
  88. * @returns
  89. */
  90. async leaveGroup(groupName: string) {
  91. if (this.SR.state === 'Connected') {
  92. // 判断是否已经建立链接 如果没有 先链接
  93. await this.SR.invoke('LeaveGroupAsync', {GroupName:groupName});
  94. }
  95. },
  96. /**
  97. * @description 关闭链接
  98. * @returns
  99. */
  100. async stop() {
  101. try {
  102. //使用async和await 或 promise的then 和catch 处理来自服务端的异常
  103. await this.SR.stop();
  104. console.log(this.SR.state, '断开链接');
  105. } catch (error) {
  106. console.log('signalR', error);
  107. }
  108. },
  109. };