webSocketStore.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // src/stores/websocket.ts
  2. import { defineStore } from "pinia";
  3. import { $root as protobuf } from "@/common/proto/proto";
  4. import * as Constant from "@/common/constant/Constant";
  5. import { useWalletStore } from "@/stores/modules/walletStore";
  6. import { getMessageApi } from "@/api/path/im.api";
  7. import { MSG_TYPE, MSG_TYPE_MAP } from "@/common/constant/msgType";
  8. const IM_PATH = import.meta.env.VITE_IM_PATH_FIlE;
  9. export const useWebSocketStore = defineStore("webSocketStore", {
  10. // 状态定义
  11. state: () => ({
  12. socket: null, // socket实例
  13. peer: null, // peer实例
  14. lockConnection: false, // 锁定连接
  15. reconnectAttempts: 0, // 重连次数
  16. maxReconnectAttempts: 5, // 最大重连次数
  17. reconnectInterval: 3000, // 重连间隔
  18. messages: [], // 消息列表
  19. toAvatar: "",
  20. unreadMessages: [], // 未读消息列表
  21. uuid: null,
  22. // 心跳检测配置
  23. heartCheck: {
  24. timeout: 10000, // 连接丢失后,多长时间内没有收到服务端的消息,则认为连接已断开
  25. timeoutObj: null, // 定时器对象
  26. serverTimeoutObj: null, // 服务器定时器对象
  27. num: 3, // 重连次数
  28. },
  29. }),
  30. // 计算属性
  31. getters: {
  32. isConnected: (state) => state.socket?.readyState === WebSocket.OPEN,
  33. hasUnreadMessages: (state) => state.unreadMessages.length > 0,
  34. },
  35. // 方法
  36. actions: {
  37. async getMessages(params) {
  38. const { data } = await getMessageApi({
  39. messageType: params.messageType,
  40. uuid: params.uuid,
  41. friendUsername: params.friendUsername,
  42. });
  43. this.messages = data.map(item =>{
  44. item.avatar = item.avatar ? IM_PATH +item.avatar : item.avatar
  45. return item
  46. }) || [];
  47. },
  48. // 初始化socket
  49. startHeartbeat() {
  50. const self = this;
  51. const _num = this.heartCheck.num;
  52. this.heartCheck.timeoutObj && clearTimeout(this.heartCheck.timeoutObj);
  53. this.heartCheck.serverTimeoutObj &&
  54. clearTimeout(this.heartCheck.serverTimeoutObj);
  55. this.heartCheck.timeoutObj = setTimeout(() => {
  56. if (this.socket?.readyState === WebSocket.OPEN) {
  57. const data = {
  58. type: "heatbeat",
  59. content: "ping",
  60. };
  61. const MessageType = protobuf.lookupType("protocol.Message");
  62. const messagePB = MessageType.create(data);
  63. const buffer = MessageType.encode(messagePB).finish();
  64. this.socket.send(buffer);
  65. }
  66. self.heartCheck.serverTimeoutObj = setTimeout(() => {
  67. _num--;
  68. if (_num <= 0) {
  69. console.log("the ping num is more then 3, close socket!");
  70. this.socket?.close();
  71. }
  72. }, self.heartCheck.timeout);
  73. }, this.heartCheck.timeout);
  74. },
  75. resetHeartbeat() {
  76. this.heartCheck.timeoutObj && clearTimeout(this.heartCheck.timeoutObj);
  77. this.heartCheck.serverTimeoutObj &&
  78. clearTimeout(this.heartCheck.serverTimeoutObj);
  79. this.heartCheck.num = 3;
  80. },
  81. // 链接ws
  82. connect(userUuid) {
  83. if (!userUuid) return;
  84. console.log("开始连接...");
  85. this.disconnect(); // 确保先断开现有连接
  86. this.peer = new RTCPeerConnection();
  87. this.socket = new WebSocket(
  88. `ws://192.168.0.59:8888/api/v1/socket.io?user=${userUuid}`
  89. );
  90. this.socket.onopen = () => {
  91. this.startHeartbeat();
  92. console.log("WebSocket连接成功");
  93. this.webrtcConnection();
  94. };
  95. this.socket.onmessage = (event) => {
  96. this.startHeartbeat();
  97. this.handleMessage(event.data);
  98. };
  99. this.socket.onclose = () => {
  100. console.log("连接关闭,尝试重新连接...");
  101. this.resetHeartbeat();
  102. this.reconnect();
  103. };
  104. this.socket.onerror = (error) => {
  105. console.error("WebSocket错误:", error);
  106. this.resetHeartbeat();
  107. this.reconnect();
  108. };
  109. },
  110. // 处理消息
  111. handleMessage(data) {
  112. const MessageType = protobuf.lookupType("protocol.Message");
  113. const reader = new FileReader();
  114. reader.onload = (event) => {
  115. try {
  116. const messagePB = MessageType.decode(
  117. new Uint8Array(event.target?.result)
  118. );
  119. const message = MessageType.toObject(messagePB, {
  120. longs: String,
  121. enums: String,
  122. bytes: String,
  123. });
  124. console.log("收到消息:", message);
  125. // 处理消息
  126. // if (MSG_TYPE_MAP.includes(message.messageType)) {
  127. // 文本消息
  128. message.avatar = this.toAvatar
  129. if (message.contentType === MSG_TYPE.TEXT) {
  130. this.messages.push({
  131. ...message,
  132. toUsername: message.to,
  133. });
  134. }
  135. // 音频消息
  136. if (message.contentType === MSG_TYPE.AUDIO) {
  137. const audioBlob = new Blob([message.file], {
  138. type: `audio/${message.fileSuffix}`,
  139. });
  140. // 生成可播放的 ObjectURL
  141. const audioUrl = URL.createObjectURL(audioBlob);
  142. this.messages.push({
  143. ...message,
  144. file: audioUrl,
  145. toUsername: message.to,
  146. });
  147. }
  148. if (message.type === "heatbeat") return;
  149. if (message.type === Constant.MESSAGE_TRANS_TYPE) {
  150. this.dealWebRtcMessage(message);
  151. return;
  152. }
  153. // 其他消息处理逻辑...
  154. } catch (error) {
  155. console.error("消息解码错误:", error);
  156. }
  157. };
  158. reader.readAsArrayBuffer(data);
  159. },
  160. // 处理WebRTC消息
  161. webrtcConnection() {
  162. if (!this.peer) return;
  163. this.peer.onicecandidate = (e) => {
  164. if (e.candidate && this.socket) {
  165. const candidate = {
  166. type: "answer_ice",
  167. iceCandidate: e.candidate,
  168. };
  169. const message = {
  170. content: JSON.stringify(candidate),
  171. type: Constant.MESSAGE_TRANS_TYPE,
  172. };
  173. this.sendMessage(message);
  174. }
  175. };
  176. this.peer.ontrack = (e) => {
  177. if (e && e.streams) {
  178. const remoteVideo = document.getElementById("remoteVideoReceiver");
  179. const remoteAudio = document.getElementById("audioPhone");
  180. if (remoteVideo) remoteVideo.srcObject = e.streams[0];
  181. if (remoteAudio) remoteAudio.srcObject = e.streams[0];
  182. }
  183. };
  184. },
  185. // 断线重连
  186. reconnect() {
  187. if (
  188. this.lockConnection ||
  189. this.reconnectAttempts >= this.maxReconnectAttempts
  190. ) {
  191. return;
  192. }
  193. this.lockConnection = true;
  194. this.reconnectAttempts++;
  195. console.log(
  196. `重新连接中... (尝试 ${this.reconnectAttempts}/${this.maxReconnectAttempts})`
  197. );
  198. setTimeout(() => {
  199. this.connect(localStorage.uuid);
  200. this.lockConnection = false;
  201. }, this.reconnectInterval);
  202. },
  203. // 重连
  204. disconnect() {
  205. if (this.socket) {
  206. this.resetHeartbeat();
  207. this.socket.close();
  208. this.socket = null;
  209. }
  210. if (this.peer) {
  211. this.peer.close();
  212. this.peer = null;
  213. }
  214. this.reconnectAttempts = 0;
  215. },
  216. // 发送消息
  217. sendMessage(messageData) {
  218. if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
  219. console.error("WebSocket未连接");
  220. return false;
  221. }
  222. const walletStore = useWalletStore();
  223. let data = {
  224. ...messageData,
  225. fromUsername: walletStore.username,
  226. from: walletStore.account,
  227. };
  228. console.log("发送消息=", data);
  229. try {
  230. const MessageType = protobuf.lookupType("protocol.Message");
  231. const messagePB = MessageType.create(data);
  232. const buffer = MessageType.encode(messagePB).finish();
  233. this.socket.send(buffer);
  234. data.avatar = walletStore.avatar
  235. // 文本消息
  236. if (data.contentType == MSG_TYPE.TEXT) {
  237. this.messages.push({
  238. ...data,
  239. toUsername: data.friendUsername,
  240. });
  241. }
  242. // 音频消息
  243. if (data.contentType === MSG_TYPE.AUDIO) {
  244. const blob = new Blob([data.file], { type: data.fileSuffix });
  245. const url = URL.createObjectURL(blob);
  246. console.log("url=",url)
  247. this.messages.push({
  248. ...data,
  249. toUsername: data.to,
  250. localUrl: url,
  251. });
  252. }
  253. return true;
  254. } catch (error) {
  255. console.error("消息编码错误:", error);
  256. return false;
  257. }
  258. },
  259. // 发送WebRTC消息
  260. dealWebRtcMessage(message) {
  261. // 实现WebRTC消息处理逻辑
  262. },
  263. },
  264. });