webSocket.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import { Socket, io } from 'socket.io-client';
  2. import { useNetworkStore } from '@/store/network';
  3. // websocket连接状态
  4. export enum WsConnectStatusEnum {
  5. /** 已连接 */
  6. connection = 'connection',
  7. /** 连接中 */
  8. connecting = 'connecting',
  9. /** 已连接 */
  10. connected = 'connected',
  11. /** 断开连接中 */
  12. disconnecting = 'disconnecting',
  13. /** 已断开连接 */
  14. disconnect = 'disconnect',
  15. /** 重新连接 */
  16. reconnect = 'reconnect',
  17. /** 客户端的已连接 */
  18. connect = 'connect',
  19. }
  20. // websocket消息类型
  21. export enum WsMsgTypeEnum {
  22. /** 用户进入聊天 */
  23. join = 'join',
  24. /** 用户进入聊天完成 */
  25. joined = 'joined',
  26. /** 用户进入聊天 */
  27. otherJoin = 'otherJoin',
  28. /** 用户退出聊天 */
  29. leave = 'leave',
  30. /** 用户退出聊天完成 */
  31. leaved = 'leaved',
  32. /** 当前所有在线用户 */
  33. liveUser = 'liveUser',
  34. /** 用户发送消息 */
  35. message = 'message',
  36. /** 房间正在直播 */
  37. roomLiveing = 'roomLiveing',
  38. /** 房间不在直播 */
  39. roomNoLive = 'roomNoLive',
  40. /** sendBlob */
  41. sendBlob = 'sendBlob',
  42. offer = 'offer',
  43. answer = 'answer',
  44. candidate = 'candidate',
  45. }
  46. export class WebSocketClass {
  47. socketIo: Socket | null = null;
  48. status: WsConnectStatusEnum = WsConnectStatusEnum.disconnect;
  49. url = '';
  50. roomId = '-1';
  51. isAdmin = false;
  52. constructor({ roomId, url, isAdmin }) {
  53. if (!window.WebSocket) {
  54. alert('当前环境不支持WebSocket!');
  55. return;
  56. }
  57. this.roomId = roomId;
  58. this.isAdmin = isAdmin;
  59. this.url = url;
  60. this.socketIo = io(url, { transports: ['websocket'], forceBase64: false });
  61. this.update();
  62. }
  63. // 发送websocket消息
  64. send = ({ msgType, data }: { msgType: WsMsgTypeEnum; data?: any }) => {
  65. console.log('【websocket】发送websocket消息', msgType, data);
  66. this.socketIo?.emit(msgType, {
  67. roomId: this.roomId,
  68. socketId: this.socketIo.id,
  69. data,
  70. isAdmin: this.isAdmin,
  71. });
  72. };
  73. // 更新store
  74. update = () => {
  75. const networkStore = useNetworkStore();
  76. networkStore.updateWsMap(this.roomId, this);
  77. };
  78. // 手动关闭websocket连接
  79. close = () => {
  80. console.warn('手动关闭websocket连接', this.socketIo?.id);
  81. this.socketIo?.close();
  82. };
  83. // 连接websocket
  84. connect = () => {};
  85. }