From 157e869a93513f842bd83d2de49ad1077ee95bd2 Mon Sep 17 00:00:00 2001 From: thiszhc <2029364173@qq.com> Date: Sat, 7 Oct 2023 23:34:39 +0800 Subject: [PATCH 1/6] =?UTF-8?q?=E6=8E=A5=E5=85=A5websocket?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.development | 3 + .env.production | 3 + src/utils/websocket.ts | 134 +++++++++++++++++++++++++++++++++++++++++ src/views/index.vue | 5 ++ 4 files changed, 145 insertions(+) create mode 100644 src/utils/websocket.ts diff --git a/.env.development b/.env.development index 6d2f8ddf..5bb03fd8 100644 --- a/.env.development +++ b/.env.development @@ -23,3 +23,6 @@ VITE_APP_RSA_PUBLIC_KEY = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbf # 客户端id VITE_APP_CLIENT_ID = 'e5cd7e4891bf95d1d19206ce24a7b32e' + +#websocket地址 +VITE_APP_WEBSOCKET_URL = 'ws://127.0.0.1:8098/resource/websocket' \ No newline at end of file diff --git a/.env.production b/.env.production index d723d2ad..5a39bd0c 100644 --- a/.env.production +++ b/.env.production @@ -26,3 +26,6 @@ VITE_APP_RSA_PUBLIC_KEY = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbf # 客户端id VITE_APP_CLIENT_ID = 'e5cd7e4891bf95d1d19206ce24a7b32e' + +#websocket地址 +VITE_APP_WEBSOCKET_URL = 'ws://127.0.0.1:8098/resource/websocket' \ No newline at end of file diff --git a/src/utils/websocket.ts b/src/utils/websocket.ts new file mode 100644 index 00000000..791b5f5a --- /dev/null +++ b/src/utils/websocket.ts @@ -0,0 +1,134 @@ +/** + * @module initWebSocket 初始化 + * @module websocketonopen 连接成功 + * @module websocketonerror 连接失败 + * @module websocketclose 断开连接 + * @module resetHeart 重置心跳 + * @module sendSocketHeart 心跳发送 + * @module reconnect 重连 + * @module sendMsg 发送数据 + * @module websocketonmessage 接收数据 + * @module test 测试收到消息传递 + * @description socket 通信 + * @param {any} url socket地址 + * @param {any} websocket websocket 实例 + * @param {any} heartTime 心跳定时器实例 + * @param {number} socketHeart 心跳次数 + * @param {number} HeartTimeOut 心跳超时时间 + * @param {number} socketError 错误次数 + */ + +import { getToken } from '@/utils/auth'; + +let socketUrl: any = ''; // socket地址 +let websocket: any = null; // websocket 实例 +let heartTime: any = null; // 心跳定时器实例 +let socketHeart = 0 as number; // 心跳次数 +const HeartTimeOut = 10000; // 心跳超时时间 10000 = 10s +let socketError = 0 as number; // 错误次数 + +// 初始化socket +export const initWebSocket = (url: any) => { + socketUrl = url; + // 初始化 websocket + websocket = new WebSocket(url + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID); + websocketonopen(); + websocketonmessage(); + websocketonerror(); + websocketclose(); + sendSocketHeart(); +}; + +onMounted(() => { + // 初始化websocket + initWebSocket(socketUrl); +}); + +// socket 连接成功 +export const websocketonopen = () => { + websocket.onopen = function (e: any) { + console.log('连接 websocket 成功', e); + resetHeart(); + }; +}; + +// socket 连接失败 +export const websocketonerror = () => { + websocket.onerror = function (e: any) { + console.log('连接 websocket 失败', e); + }; +}; + +// socket 断开链接 +export const websocketclose = () => { + websocket.onclose = function (e: any) { + console.log('断开连接', e); + }; +}; + +// socket 重置心跳 +export const resetHeart = () => { + socketHeart = 0; + socketError = 0; + clearInterval(heartTime); + sendSocketHeart(); +}; + +// socket心跳发送 +export const sendSocketHeart = () => { + console.log(websocket); + heartTime = setInterval(() => { + // 如果连接正常则发送心跳 + if (websocket.readyState == 1) { + // if (socketHeart <= 30) { + websocket.send( + JSON.stringify({ + type: 'ping' + }) + ); + socketHeart = socketHeart + 1; + } else { + // 重连 + reconnect(); + } + }, HeartTimeOut); +}; + +// socket重连 +export const reconnect = () => { + if (socketError <= 2) { + clearInterval(heartTime); + initWebSocket(socketUrl); + socketError = socketError + 1; + // eslint-disable-next-line prettier/prettier + console.log('socket重连', socketError); + } else { + // eslint-disable-next-line prettier/prettier + console.log('重试次数已用完'); + clearInterval(heartTime); + } +}; + +// socket 发送数据 +export const sendMsg = (data: any) => { + websocket.send(data); +}; + +// socket 接收数据 +export const websocketonmessage = () => { + websocket.onmessage = function (e: any) { + const msg = JSON.parse(e.data) as any; + if (msg.type === 'heartbeat') { + resetHeart(); + console.log('心跳'); + } + if (msg.type === 'ping') { + console.log('收到心跳', socketHeart); + return; + } + ElNotification({ + title: '收到一条消息', + message: msg + }); + }; +}; diff --git a/src/views/index.vue b/src/views/index.vue index 438c1afc..e740ac60 100644 --- a/src/views/index.vue +++ b/src/views/index.vue @@ -96,6 +96,11 @@ diff --git a/src/store/modules/notice.ts b/src/store/modules/notice.ts new file mode 100644 index 00000000..2f645a6f --- /dev/null +++ b/src/store/modules/notice.ts @@ -0,0 +1,33 @@ +import { defineStore } from 'pinia'; + +interface NoticeItem { + title?: string; + message: any; + time: string; +} + +export const useNoticeStore = defineStore('notice', () => { + const state = reactive({ + notices: [] as NoticeItem[] + }); + + const addNotice = (notice: NoticeItem) => { + state.notices.push(notice); + }; + + const removeNotice = (notice: NoticeItem) => { + state.notices.splice(state.notices.indexOf(notice), 1); + }; + + const clearNotice = () => { + state.notices = []; + }; + return { + state, + addNotice, + removeNotice, + clearNotice + }; +}); + +export default useNoticeStore; diff --git a/src/utils/websocket.ts b/src/utils/websocket.ts index 791b5f5a..0560ed46 100644 --- a/src/utils/websocket.ts +++ b/src/utils/websocket.ts @@ -19,6 +19,9 @@ */ import { getToken } from '@/utils/auth'; +import useNoticeStore from '@/store/modules/notice'; + +const { addNotice } = useNoticeStore(); let socketUrl: any = ''; // socket地址 let websocket: any = null; // websocket 实例 @@ -37,17 +40,13 @@ export const initWebSocket = (url: any) => { websocketonerror(); websocketclose(); sendSocketHeart(); + return websocket; }; -onMounted(() => { - // 初始化websocket - initWebSocket(socketUrl); -}); - // socket 连接成功 export const websocketonopen = () => { - websocket.onopen = function (e: any) { - console.log('连接 websocket 成功', e); + websocket.onopen = function () { + console.log('连接 websocket 成功'); resetHeart(); }; }; @@ -76,7 +75,6 @@ export const resetHeart = () => { // socket心跳发送 export const sendSocketHeart = () => { - console.log(websocket); heartTime = setInterval(() => { // 如果连接正常则发送心跳 if (websocket.readyState == 1) { @@ -120,15 +118,14 @@ export const websocketonmessage = () => { const msg = JSON.parse(e.data) as any; if (msg.type === 'heartbeat') { resetHeart(); - console.log('心跳'); } if (msg.type === 'ping') { - console.log('收到心跳', socketHeart); return; } - ElNotification({ - title: '收到一条消息', - message: msg + addNotice({ + message: msg, + time: new Date().toLocaleString() }); + return msg; }; }; diff --git a/src/views/tool/webSocket/index.vue b/src/views/tool/webSocket/index.vue new file mode 100644 index 00000000..35176661 --- /dev/null +++ b/src/views/tool/webSocket/index.vue @@ -0,0 +1,63 @@ + + + + -- Gitee From 9150b883341ff29fa91b3d1ea55c7fe3c16d9732 Mon Sep 17 00:00:00 2001 From: thiszhc <2029364173@qq.com> Date: Wed, 18 Oct 2023 10:53:05 +0800 Subject: [PATCH 3/6] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=88=9D=E5=A7=8B?= =?UTF-8?q?=E5=8C=96=E9=93=BE=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/layout/components/Navbar.vue | 2 ++ src/views/tool/webSocket/index.vue | 4 ---- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/layout/components/Navbar.vue b/src/layout/components/Navbar.vue index 03fcedb7..eafaaff8 100644 --- a/src/layout/components/Navbar.vue +++ b/src/layout/components/Navbar.vue @@ -98,12 +98,14 @@ import { ComponentInternalInstance } from "vue"; import { TenantVO } from "@/api/types"; import notice from './notice/index.vue'; import useNoticeStore from '@/store/modules/notice'; +import { getToken } from '@/utils/auth'; const appStore = useAppStore(); const userStore = useUserStore(); const settingsStore = useSettingsStore(); const noticeStore = storeToRefs(useNoticeStore()); const newNotice = ref(0); +let websocket = new WebSocket(import.meta.env.VITE_APP_WEBSOCKET_URL + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID); const { proxy } = getCurrentInstance() as ComponentInternalInstance; const userId = ref(userStore.userId); diff --git a/src/views/tool/webSocket/index.vue b/src/views/tool/webSocket/index.vue index 35176661..4452bb0b 100644 --- a/src/views/tool/webSocket/index.vue +++ b/src/views/tool/webSocket/index.vue @@ -50,10 +50,6 @@ const start = () => { const sendMessage = () => { sendMsg(conf.send); }; - -onMounted(() => { - start(); -}); -- Gitee From de6f852acafadea8e313332a7b990bbccba8467c Mon Sep 17 00:00:00 2001 From: thiszhc <2029364173@qq.com> Date: Thu, 2 Nov 2023 10:59:26 +0800 Subject: [PATCH 6/6] =?UTF-8?q?=E5=9B=9E=E6=BB=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.development | 2 +- .env.production | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.env.development b/.env.development index dd1d065d..6d2f8ddf 100644 --- a/.env.development +++ b/.env.development @@ -22,4 +22,4 @@ VITE_APP_PORT = 80 VITE_APP_RSA_PUBLIC_KEY = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdHnzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ==' # 客户端id -VITE_APP_CLIENT_ID = 'e5cd7e4891bf95d1d19206ce24a7b32e' \ No newline at end of file +VITE_APP_CLIENT_ID = 'e5cd7e4891bf95d1d19206ce24a7b32e' diff --git a/.env.production b/.env.production index 07785916..d723d2ad 100644 --- a/.env.production +++ b/.env.production @@ -25,4 +25,4 @@ VITE_APP_PORT = 80 VITE_APP_RSA_PUBLIC_KEY = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdHnzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ==' # 客户端id -VITE_APP_CLIENT_ID = 'e5cd7e4891bf95d1d19206ce24a7b32e' \ No newline at end of file +VITE_APP_CLIENT_ID = 'e5cd7e4891bf95d1d19206ce24a7b32e' -- Gitee