signalR.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 store from '../store'
  4. import { getToken } from '@/utils/auth'
  5. import { Notification } from 'element-ui'
  6. export default {
  7. // signalR对象
  8. SR: {},
  9. // 失败连接重试次数
  10. failNum: 4,
  11. baseUrl: '',
  12. init(url) {
  13. const connection = new signalR.HubConnectionBuilder()
  14. .withUrl(url, { accessTokenFactory: () => getToken() })
  15. .withAutomaticReconnect()//自动重新连接
  16. .configureLogging(signalR.LogLevel.Information)
  17. .build();
  18. this.SR = connection;
  19. // 断线重连
  20. connection.onclose(async () => {
  21. console.log('断开连接了')
  22. console.assert(connection.state === signalR.HubConnectionState.Disconnected);
  23. // 建议用户重新刷新浏览器
  24. await this.start();
  25. })
  26. connection.onreconnected(() => {
  27. console.log('断线重新连接成功')
  28. })
  29. this.receiveMsg(connection);
  30. // 启动
  31. // this.start();
  32. },
  33. /**
  34. * 调用 this.signalR.start().then(async () => { await this.SR.invoke("method")})
  35. * @returns
  36. */
  37. async start() {
  38. var that = this;
  39. try {
  40. //使用async和await 或 promise的then 和catch 处理来自服务端的异常
  41. await this.SR.start();
  42. //console.assert(this.SR.state === signalR.HubConnectionState.Connected);
  43. console.log('signalR 连接成功了', this.SR.state);
  44. return true;
  45. } catch (error) {
  46. that.failNum--;
  47. console.log(`失败重试剩余次数${that.failNum}`, error)
  48. if (that.failNum > 0) {
  49. setTimeout(async () => {
  50. await this.SR.start()
  51. }, 5000);
  52. }
  53. return false;
  54. }
  55. },
  56. // 接收消息处理
  57. receiveMsg(connection) {
  58. connection.on("onlineNum", (data) => {
  59. store.dispatch("socket/changeOnlineNum", data);
  60. });
  61. // 接收欢迎语
  62. connection.on("welcome", (data) => {
  63. console.log('welcome', data)
  64. Notification.info(data)
  65. });
  66. // 接收后台手动推送消息
  67. connection.on("receiveNotice", (title, data) => {
  68. Notification({
  69. type: 'info',
  70. title: title,
  71. message: data,
  72. dangerouslyUseHTMLString: true,
  73. duration: 0
  74. })
  75. })
  76. // 接收系统通知/公告
  77. connection.on("moreNotice", (data) => {
  78. if (data.code == 200) {
  79. store.dispatch("socket/getNoticeList", data.data);
  80. }
  81. })
  82. }
  83. }