123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- import {ElMessageBox} from 'element-plus'
- import Cookies from 'js-cookie'
- import router from '@/router'
- import store from '@/store'
- const socketUrl = import.meta.env.VITE_SOCKET_URL
- let webSocket = null
- let globalCallback = new Map()
- export function closeWebSocket() {
- store.commit('user/closeSid')
- if (webSocket !== null) {
- webSocket.close()
- webSocket = null
- }
- }
- export function setCallback(messageName, callback) {
- globalCallback.set(messageName, callback)
- }
- export function delCallback(messageName) {
- globalCallback.delete(messageName)
- }
- export function sendAMessage(name, data) {
- if (globalCallback.has(name)) {
- try {
- globalCallback.get(name)(data)
- } catch {
- }
- }
- }
- export const socketErrDialog = ref(false)
- export function initWebSocket(sid, force) {
- if ('WebSocket' in window) {
- if (webSocket === null || force) {
- const url = socketUrl + sid
- webSocket = new WebSocket(url)
- }
- } else {
- alert('该浏览器不支持websocket!')
- webSocket = 'unsupport'
- }
- webSocket.onopen = function () {
- socketErrDialog.value = false
- store.commit('user/sidChange', sid)
- console.log('WebSocket连接')
- }
- webSocket.onmessage = function (e) {
- let data = JSON.parse(e.data)
- sendAMessage(data.name, data.message)
- }
- webSocket.onclose = function () {
- if (router.currentRoute.value.path === '/login') {
- location.reload()
- } else {
- socketErrDialog.value = true
- }
- webSocket = null
- let sid
- if (router.currentRoute.value.path === '/triageRoomScreen') {
- sid = Cookies.get('room-screen-sid')
- } else {
- sid = store.state.user.sid
- }
- if (!sid) {
- if (router.currentRoute.value.path === '/login') {
- return
- }
- ElMessageBox.confirm('未检测到WebSocket连接的sid,请重新登录。', '提示', {
- showCancelButton: false,
- type: 'warning',
- }).then(async () => {
- await router.push('/login')
- }).catch(async () => {
- await router.push('/login')
- })
- } else {
- if (router.currentRoute.value.path === '/triageFloorScreen') {
- sid += '-triageFloorScreen'
- }
- setTimeout(() => {
- initWebSocket(sid)
- }, 3000)
- }
- }
- webSocket.onerror = function () {
- console.error('WebSocket连接发生错误')
- }
- }
|