1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- import user, { UserRole } from '~/store/user';
- export type TSocketRes<T> = {
- content: T
- from_client_id: string
- from_client_name: string
- time: string
- to_client_id: string
- type: string
- }
- const CLIENT_NAME = `${user.user_id}|${user.user_realname}|${UserRole}`
- export function createSocket(
- options: { teacher: string, student: string },
- hooks: {
- message: Function
- }
- ) {
- const ws = new WebSocket("wss://socket.bozedu.net")
- ws.addEventListener('message', (e) => {
- if (e.data) {
- try {
- const data: TSocketRes<string> = JSON.parse(e.data)
- if (CLIENT_NAME === data.from_client_name) return
- if (!['ping'].includes(data.type)) {
- console.groupCollapsed(`Socket : ${data.type}-${data.from_client_name}`)
- console.log(data);
- console.groupEnd();
- }
- if (data.type === 'login') {
- }
- if (data.type === 'say') {
- const content = {
- ...data,
- content: JSON.parse(decodeURIComponent(data.content))
- }
- console.groupCollapsed(`├─ Socket Say:`)
- console.log(content);
- console.groupEnd();
- hooks.message(content)
- }
- } catch (error) {
- console.error(error);
- }
- }
- })
- ws.addEventListener('error', (err) => {
- console.error('ws error :>> ', ws, err);
- })
- ws.addEventListener('open', (e) => {
- ws.send(JSON.stringify({
- "type": "login",
- "client_name": CLIENT_NAME,
- "room_id": `aiwen_consult_${options.teacher}_${options.student}`
- }))
- })
- return ws
- }
- export function socketSend(ws: WebSocket, content: unknown) {
- if (ws.readyState === WebSocket.OPEN) {
- // WebSocket 连接已建立
- ws.send(
- JSON.stringify({
- type: "say",
- to_client_id: 'all',
- content: encodeURIComponent(JSON.stringify(content))
- })
- )
- } else {
- ws.onopen = () => {
- ws.send(
- JSON.stringify({
- type: "say",
- to_client_id: 'all',
- content: encodeURIComponent(JSON.stringify(content))
- })
- )
- }
- }
- }
|