feat: 项目初始化、完成基本流式传输和语音识别功能
This commit is contained in:
66
web/src/services/websocket.ts
Normal file
66
web/src/services/websocket.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { useChatStore } from "@/stores";
|
||||
|
||||
// WebSocket
|
||||
export const useWebSocketStore = defineStore("websocket", () => {
|
||||
const websocket = ref<WebSocket>();
|
||||
const connected = ref(false);
|
||||
const chatStore = useChatStore();
|
||||
|
||||
const { onlineCount } = storeToRefs(chatStore);
|
||||
|
||||
const onmessage = (e: MessageEvent) => {
|
||||
const data = JSON.parse(e.data);
|
||||
switch (data.type) {
|
||||
case "count":
|
||||
onlineCount.value = data.online_count;
|
||||
break;
|
||||
case "asr_result":
|
||||
chatStore.addMessageToHistory(data.result);
|
||||
}
|
||||
};
|
||||
|
||||
const send = (data: string) => {
|
||||
if (websocket.value && websocket.value.readyState === WebSocket.OPEN)
|
||||
websocket.value?.send(data);
|
||||
};
|
||||
const close = () => {
|
||||
websocket.value?.close();
|
||||
};
|
||||
|
||||
const connect = () => {
|
||||
const url = "ws://127.0.0.1:8000/websocket";
|
||||
websocket.value = new WebSocket(url);
|
||||
|
||||
websocket.value.onopen = () => {
|
||||
connected.value = true;
|
||||
|
||||
let pingIntervalId: NodeJS.Timeout | undefined;
|
||||
|
||||
if (pingIntervalId)
|
||||
clearInterval(pingIntervalId);
|
||||
pingIntervalId = setInterval(() => send("ping"), 30 * 1000);
|
||||
|
||||
if (websocket.value) {
|
||||
websocket.value.onmessage = onmessage;
|
||||
|
||||
websocket.value.onerror = (e: Event) => {
|
||||
console.error(`WebSocket错误:${(e as ErrorEvent).message}`);
|
||||
};
|
||||
websocket.value.onclose = () => {
|
||||
connected.value = false;
|
||||
setTimeout(() => {
|
||||
connect(); // 尝试重新连接
|
||||
}, 1000); // 1秒后重试连接
|
||||
};
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
websocket,
|
||||
connected,
|
||||
send,
|
||||
close,
|
||||
connect,
|
||||
};
|
||||
});
|
||||
Reference in New Issue
Block a user