diff --git a/core/core-frontend/src/websocket/index.ts b/core/core-frontend/src/websocket/index.ts index 3ccc8612fe..33ebd4cc0f 100644 --- a/core/core-frontend/src/websocket/index.ts +++ b/core/core-frontend/src/websocket/index.ts @@ -1,7 +1,12 @@ import SockJS from 'sockjs-client/dist/sockjs.min.js' import Stomp from 'stompjs' import eventBus from '@/utils/eventBus' +import { useCache } from '@/hooks/web/useCache' +import { ref } from 'vue' +const { wsCache } = useCache() let stompClient: Stomp.Client +let timeInterval: NodeJS.Timer | null = null +const isDisconnect = ref(true) export default { install() { @@ -11,25 +16,80 @@ export default { event: 'task-export-topic-call' } ] + let prefix = '/' + if (window.DataEaseBi?.baseUrl) { + prefix = window.DataEaseBi.baseUrl + } else { + const href = window.location.href + prefix = href.substring(0, href.indexOf('#')) + } - // const socket = new SockJS('http://localhost:8100' + '/websocket' + '?userId=1') - // stompClient = Stomp.over(socket) - // const heads = { - // userId: 1 - // } - // stompClient.connect( - // heads, - // res => { - // console.log('连接成功: ' + res) - // channels.forEach(channel => { - // stompClient.subscribe('/user/' + 1 + channel.topic, res => { - // res && res.body && eventBus.emit(channel.event, res.body) - // }) - // }) - // }, - // error => { - // console.log('连接失败: ' + error) - // } - // ) + function isLoginStatus() { + return wsCache.get('user.token') + } + + function connection() { + if (!isLoginStatus()) { + return + } + let prefix = '/' + if (window.DataEaseBi?.baseUrl) { + prefix = window.DataEaseBi.baseUrl + } else { + const href = window.location.href + prefix = href.substring(0, href.indexOf('#')) + } + const socket = new SockJS(prefix + 'websocket?userId=' + wsCache.get('user.uid')) + stompClient = Stomp.over(socket) + const heads = { + userId: wsCache.get('user.uid') + } + stompClient.connect( + heads, + res => { + isDisconnect.value = false + channels.forEach(channel => { + stompClient.subscribe('/user/' + wsCache.get('user.uid') + channel.topic, res => { + res && res.body && eventBus.emit(channel.event, res.body) + }) + }) + }, + error => { + console.log('连接失败: ' + error) + } + ) + } + + function disconnect() { + if (!isDisconnect.value && stompClient != undefined) { + stompClient.disconnect( + function () { + isDisconnect.value = true + }, + function (error) { + isDisconnect.value = false + } + ) + } + } + + function initialize() { + connection() + timeInterval = setInterval(() => { + if (!isLoginStatus()) { + disconnect() + return + } + if (isDisconnect.value) { + connection() + } + try { + stompClient.send('heart detection') + } catch (error) { + connection() + } + }, 5000) + } + initialize() } }