websocket.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. }
  44. webSocket.onmessage = function (e) {
  45. let data = JSON.parse(e.data)
  46. sendAMessage(data.name, data.message)
  47. }
  48. webSocket.onclose = function () {
  49. if (router.currentRoute.value.path === '/login') {
  50. location.reload()
  51. } else {
  52. socketErrDialog.value = true
  53. }
  54. webSocket = null
  55. let sid
  56. if (router.currentRoute.value.path === '/triageRoomScreen') {
  57. sid = Cookies.get('room-screen-sid')
  58. } else {
  59. sid = store.state.user.sid
  60. }
  61. if (!sid) {
  62. if (router.currentRoute.value.path === '/login') {
  63. return
  64. }
  65. ElMessageBox.confirm('未检测到WebSocket连接的sid,请重新登录。', '提示', {
  66. showCancelButton: false,
  67. type: 'warning',
  68. }).then(async () => {
  69. await router.push('/login')
  70. }).catch(async () => {
  71. await router.push('/login')
  72. })
  73. } else {
  74. if (router.currentRoute.value.path === '/triageFloorScreen') {
  75. sid += '-triageFloorScreen'
  76. }
  77. setTimeout(() => {
  78. initWebSocket(sid)
  79. }, 3000)
  80. }
  81. }
  82. webSocket.onerror = function () {
  83. console.error('WebSocket连接发生错误')
  84. }
  85. }