websocket.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import {ElMessageBox} from 'element-plus'
  2. import Cookies from 'js-cookie'
  3. import router from '@/router'
  4. import store from '@/store'
  5. const socketUrl = import.meta.env.VITE_SOCKET_URL
  6. let webSocket = null
  7. let globalCallback = new Map()
  8. export function closeWebSocket() {
  9. store.commit('user/closeSid')
  10. if (webSocket !== null) {
  11. webSocket.close()
  12. webSocket = null
  13. }
  14. }
  15. export function setCallback(messageName, callback) {
  16. globalCallback.set(messageName, callback)
  17. }
  18. export function delCallback(messageName) {
  19. globalCallback.delete(messageName)
  20. }
  21. export function sendAMessage(name, data) {
  22. if (globalCallback.has(name)) {
  23. try {
  24. globalCallback.get(name)(data)
  25. } catch {
  26. }
  27. }
  28. }
  29. export const socketErrDialog = ref(false)
  30. export function initWebSocket(sid, force) {
  31. if ('WebSocket' in window) {
  32. if (webSocket === null || force) {
  33. const url = socketUrl + sid
  34. webSocket = new WebSocket(url)
  35. }
  36. } else {
  37. alert('该浏览器不支持websocket!')
  38. webSocket = 'unsupport'
  39. }
  40. webSocket.onopen = function () {
  41. socketErrDialog.value = false
  42. store.commit('user/sidChange', sid)
  43. console.log('WebSocket连接')
  44. }
  45. webSocket.onmessage = function (e) {
  46. let data = JSON.parse(e.data)
  47. sendAMessage(data.name, data.message)
  48. }
  49. webSocket.onclose = function () {
  50. if (router.currentRoute.value.path === '/login') {
  51. location.reload()
  52. } else {
  53. socketErrDialog.value = true
  54. }
  55. webSocket = null
  56. let sid
  57. if (router.currentRoute.value.path === '/triageRoomScreen') {
  58. sid = Cookies.get('room-screen-sid')
  59. } else {
  60. sid = store.state.user.sid
  61. }
  62. if (!sid) {
  63. if (router.currentRoute.value.path === '/login') {
  64. return
  65. }
  66. ElMessageBox.confirm('未检测到WebSocket连接的sid,请重新登录。', '提示', {
  67. showCancelButton: false,
  68. type: 'warning',
  69. }).then(async () => {
  70. await router.push('/login')
  71. }).catch(async () => {
  72. await router.push('/login')
  73. })
  74. } else {
  75. if (router.currentRoute.value.path === '/triageFloorScreen') {
  76. sid += '-triageFloorScreen'
  77. }
  78. setTimeout(() => {
  79. initWebSocket(sid)
  80. }, 3000)
  81. }
  82. }
  83. webSocket.onerror = function () {
  84. console.error('WebSocket连接发生错误')
  85. }
  86. }