ws.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import { isDevMode } from '@/utils/env'
  2. import { message } from 'antd'
  3. import type { MessageType } from '@/types/typing'
  4. import wsNotice from '@/components/RightContent/Book/wsNotice'
  5. enum ReadyState {
  6. Connecting = 0,
  7. Open = 1,
  8. Closing = 2,
  9. Closed = 3
  10. }
  11. export enum CmdType {
  12. /** @name 通知、消息 */
  13. NoticeOrMessage = 13,
  14. /** @name 在线员工列表 */
  15. OnlineBook = 12,
  16. /** @name 员工工作状态 */
  17. WorkStatus = 14
  18. }
  19. interface Options {
  20. // reconnectLimit?: number;
  21. // reconnectInterval?: number;
  22. onOpen?: (event: WebSocketEventMap['open']) => void
  23. onClose?: (event: WebSocketEventMap['close']) => void
  24. onMessage?: (message: WebSocketEventMap['message']) => void
  25. onError?: (event: WebSocketEventMap['error']) => void
  26. }
  27. class Ws {
  28. public uri: string // websocket 链接地址
  29. public opts?: Options // websocket 链接相关配置
  30. private isLock: boolean // 防止多次重连
  31. public timeout?: number // ♥跳间隔时长
  32. public wsIns: WebSocket | undefined // websocket实例
  33. // 初始化socket,一般在应用启动时初始化一次就好了,或者需要更换wsUrl
  34. public init(uri: string, opts?: Options) {
  35. this.uri = uri
  36. this.opts = opts
  37. this.connectWs()
  38. }
  39. // 利用promise封装,解决ws可能没有实例化
  40. public getInstance(): Promise<WebSocket> {
  41. return new Promise((resolve, reject) => {
  42. if (this.wsIns?.readyState === ReadyState.Open) {
  43. resolve(this.wsIns)
  44. } else if (this.wsIns) {
  45. this.connectWs()
  46. resolve(this.wsIns)
  47. } else {
  48. reject()
  49. }
  50. })
  51. }
  52. private connectWs() {
  53. try {
  54. this.wsIns = new WebSocket(this.uri)
  55. this.wsIns.onmessage = msg => {
  56. this.opts?.onMessage?.(JSON.parse(msg.data))
  57. }
  58. this.wsIns.onclose = event => {
  59. this.opts?.onClose?.(event)
  60. }
  61. this.wsIns.onerror = err => {
  62. this.opts?.onError?.(err)
  63. }
  64. } catch (error) {
  65. // 未来要做心跳机制
  66. if (isDevMode()) {
  67. message.error(error.toString())
  68. }
  69. this.wsIns = undefined
  70. }
  71. }
  72. public sendMessage(map: MessageType) {
  73. if (this.wsIns?.readyState === ReadyState.Open) {
  74. this.wsIns.send(JSON.stringify(map))
  75. }
  76. }
  77. public disconnect() {
  78. if (this.wsIns?.readyState === ReadyState.Open) {
  79. this.wsIns.close()
  80. }
  81. }
  82. }
  83. export function onMessage(msg: MessageType) {
  84. // 这里执行所有的message监听事件
  85. switch (msg.cmd) {
  86. // 通知、消息
  87. case CmdType.NoticeOrMessage:
  88. wsNotice(msg)
  89. break
  90. // 在线员工列表
  91. case CmdType.OnlineBook:
  92. break
  93. default:
  94. break
  95. }
  96. }
  97. export default new Ws()