refactor websocket message protocol, keep the only connection for all clients

This commit is contained in:
RockYang
2024-09-27 17:50:54 +08:00
parent 6ef09c8ad5
commit d95fab11be
29 changed files with 407 additions and 567 deletions

View File

@@ -1,5 +1,6 @@
import {httpGet} from "@/utils/http";
import Storage from "good-storage";
import {randString} from "@/utils/libs";
const userDataKey = "USER_INFO_CACHE_KEY"
const adminDataKey = "ADMIN_INFO_CACHE_KEY"
@@ -70,4 +71,14 @@ export function getLicenseInfo() {
resolve(err)
})
})
}
export function getClientId() {
let clientId = Storage.get('client_id')
if (clientId) {
return clientId
}
clientId = randString(42)
Storage.set('client_id', clientId)
return clientId
}

View File

@@ -6,6 +6,8 @@ export const useSharedStore = defineStore('shared', {
showLoginDialog: false,
chatListStyle: Storage.get("chat_list_style","chat"),
chatStream: Storage.get("chat_stream",true),
socket: WebSocket,
messageHandlers:{},
}),
getters: {},
actions: {
@@ -19,6 +21,36 @@ export const useSharedStore = defineStore('shared', {
setChatStream(value) {
this.chatStream = value;
Storage.set("chat_stream", value);
},
setSocket(value) {
this.socket = value;
},
addMessageHandler(key, callback) {
if (!this.messageHandlers[key]) {
this.messageHandlers[key] = callback;
this.setMessageHandler(callback)
}
},
setMessageHandler(callback) {
if (this.socket instanceof WebSocket && this.socket.readyState === WebSocket.OPEN) {
this.socket.addEventListener('message', (event) => {
try {
if (event.data instanceof Blob) {
const reader = new FileReader();
reader.readAsText(event.data, "UTF-8");
reader.onload = () => {
callback(JSON.parse(String(reader.result)))
}
}
} catch (e) {
console.warn(e)
}
})
} else {
setTimeout(() => {
this.setMessageHandler(callback)
}, 1000)
}
}
}
});

View File

@@ -6,7 +6,6 @@
// * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import Storage from "good-storage";
import {useRouter} from "vue-router";
const MOBILE_THEME = process.env.VUE_APP_KEY_PREFIX + "MOBILE_THEME"
const ADMIN_THEME = process.env.VUE_APP_KEY_PREFIX + "ADMIN_THEME"
@@ -71,4 +70,4 @@ export function setRoute(path) {
export function getRoute() {
return Storage.get(process.env.VUE_APP_KEY_PREFIX + 'ROUTE_')
}
}