websocket.js 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. /**
  2. * WebSocket工具类 - 酒店客房送餐系统
  3. * 用于实时接收新订单通知和状态变更
  4. */
  5. class HotelWebSocket {
  6. constructor() {
  7. this.ws = null
  8. this.reconnectTimer = null
  9. this.heartbeatTimer = null
  10. this.isConnected = false
  11. this.token = null
  12. }
  13. /**
  14. * 连接WebSocket
  15. * @param {string} token - WebSocket认证Token
  16. * @param {Function} onMessage - 消息回调
  17. * @param {Function} onError - 错误回调
  18. */
  19. connect(token, onMessage, onError) {
  20. if (this.isConnected) {
  21. console.warn('WebSocket已连接')
  22. return
  23. }
  24. this.token = token
  25. const wsUrl = `ws://127.0.0.1:9529/ws/hotel?token=${token}`
  26. try {
  27. this.ws = new WebSocket(wsUrl)
  28. this.ws.onopen = () => {
  29. this.isConnected = true
  30. console.log('✅ WebSocket连接成功')
  31. this.startHeartbeat()
  32. if (onMessage) {
  33. this.ws.addEventListener('message', onMessage)
  34. }
  35. }
  36. this.ws.onmessage = (event) => {
  37. const message = JSON.parse(event.data)
  38. console.log('📨 收到WebSocket消息:', message)
  39. // 根据消息类型处理
  40. if (message.type === 'NEW_ORDER') {
  41. this.handleNewOrder(message.data)
  42. } else if (message.type === 'ORDER_STATUS_CHANGED') {
  43. this.handleStatusChange(message.data)
  44. }
  45. }
  46. this.ws.onerror = (error) => {
  47. console.error('❌ WebSocket错误:', error)
  48. this.isConnected = false
  49. if (onError) {
  50. onError(error)
  51. }
  52. }
  53. this.ws.onclose = () => {
  54. console.log('🔌 WebSocket连接关闭')
  55. this.isConnected = false
  56. this.stopHeartbeat()
  57. this.attemptReconnect(onMessage, onError)
  58. }
  59. } catch (error) {
  60. console.error('WebSocket连接失败:', error)
  61. this.attemptReconnect(onMessage, onError)
  62. }
  63. }
  64. /**
  65. * 断开连接
  66. */
  67. disconnect() {
  68. if (this.ws) {
  69. this.ws.close()
  70. this.ws = null
  71. }
  72. this.isConnected = false
  73. this.stopHeartbeat()
  74. if (this.reconnectTimer) {
  75. clearTimeout(this.reconnectTimer)
  76. this.reconnectTimer = null
  77. }
  78. }
  79. /**
  80. * 发送消息
  81. */
  82. send(data) {
  83. if (this.isConnected && this.ws.readyState === WebSocket.OPEN) {
  84. this.ws.send(JSON.stringify(data))
  85. } else {
  86. console.warn('WebSocket未连接,无法发送消息')
  87. }
  88. }
  89. /**
  90. * 尝试重连
  91. */
  92. attemptReconnect(onMessage, onError) {
  93. if (this.reconnectTimer) {
  94. return
  95. }
  96. console.log('⏳ 3秒后尝试重连...')
  97. this.reconnectTimer = setTimeout(() => {
  98. this.reconnectTimer = null
  99. if (this.token) {
  100. this.connect(this.token, onMessage, onError)
  101. }
  102. }, 3000)
  103. }
  104. /**
  105. * 开始心跳
  106. */
  107. startHeartbeat() {
  108. this.heartbeatTimer = setInterval(() => {
  109. if (this.isConnected) {
  110. this.send({ type: 'PING' })
  111. }
  112. }, 30000) // 每30秒发送一次心跳
  113. }
  114. /**
  115. * 停止心跳
  116. */
  117. stopHeartbeat() {
  118. if (this.heartbeatTimer) {
  119. clearInterval(this.heartbeatTimer)
  120. this.heartbeatTimer = null
  121. }
  122. }
  123. /**
  124. * 处理新订单
  125. */
  126. handleNewOrder(order) {
  127. console.log('🆕 新订单:', order)
  128. // 触发自定义事件,供Vue组件监听
  129. window.dispatchEvent(new CustomEvent('hotel-new-order', { detail: order }))
  130. }
  131. /**
  132. * 处理订单状态变更
  133. */
  134. handleStatusChange(data) {
  135. console.log('📊 订单状态变更:', data)
  136. window.dispatchEvent(new CustomEvent('hotel-order-status-changed', { detail: data }))
  137. }
  138. }
  139. // 导出单例
  140. export default new HotelWebSocket()