ws.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import user, { UserRole } from '~/store/user';
  2. export type TSocketRes<T> = {
  3. content: T
  4. from_client_id: string
  5. from_client_name: string
  6. time: string
  7. to_client_id: string
  8. type: string
  9. }
  10. const CLIENT_NAME = `${user.user_id}|${user.user_realname}|${UserRole}`
  11. export function createSocket(
  12. options: { teacher: string, student: string },
  13. hooks: {
  14. message: Function
  15. }
  16. ) {
  17. const ws = new WebSocket("wss://socket.bozedu.net")
  18. ws.addEventListener('message', (e) => {
  19. if (e.data) {
  20. try {
  21. const data: TSocketRes<string> = JSON.parse(e.data)
  22. if (CLIENT_NAME === data.from_client_name) return
  23. if (!['ping'].includes(data.type)) {
  24. console.groupCollapsed(`Socket : ${data.type}-${data.from_client_name}`)
  25. console.log(data);
  26. console.groupEnd();
  27. }
  28. if (data.type === 'login') {
  29. }
  30. if (data.type === 'say') {
  31. const content = {
  32. ...data,
  33. content: JSON.parse(decodeURIComponent(data.content))
  34. }
  35. console.groupCollapsed(`├─ Socket Say:`)
  36. console.log(content);
  37. console.groupEnd();
  38. hooks.message(content)
  39. }
  40. } catch (error) {
  41. console.error(error);
  42. }
  43. }
  44. })
  45. ws.addEventListener('error', (err) => {
  46. console.error('ws error :>> ', ws, err);
  47. })
  48. ws.addEventListener('open', (e) => {
  49. ws.send(JSON.stringify({
  50. "type": "login",
  51. "client_name": CLIENT_NAME,
  52. "room_id": `aiwen_consult_${options.teacher}_${options.student}`
  53. }))
  54. })
  55. return ws
  56. }
  57. export function socketSend(ws: WebSocket, content: unknown) {
  58. if (ws.readyState === WebSocket.OPEN) {
  59. // WebSocket 连接已建立
  60. ws.send(
  61. JSON.stringify({
  62. type: "say",
  63. to_client_id: 'all',
  64. content: encodeURIComponent(JSON.stringify(content))
  65. })
  66. )
  67. } else {
  68. ws.onopen = () => {
  69. ws.send(
  70. JSON.stringify({
  71. type: "say",
  72. to_client_id: 'all',
  73. content: encodeURIComponent(JSON.stringify(content))
  74. })
  75. )
  76. }
  77. }
  78. }