presence-manager.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /**
  2. * 用户在线状态管理器
  3. * 基于WebSocket心跳检测实现
  4. */
  5. class PresenceManager {
  6. constructor() {
  7. this.ws = null;
  8. this.heartbeatTimer = null;
  9. this.reconnectTimer = null;
  10. this.heartbeatInterval = 30000; // 30秒心跳
  11. this.reconnectInterval = 5000; // 5秒重连
  12. this.isConnected = false;
  13. this.userId = null;
  14. this.statusCallbacks = new Map(); // 存储状态变化回调
  15. this.onlineStatusCache = new Map(); // 缓存在线状态
  16. // WebSocket服务器地址(使用实际的聊天WebSocket服务)
  17. this.wsUrl = 'ws://localhost:1004/ws/chat';
  18. this.httpUrl = 'http://localhost:1004/api/online'; // HTTP API地址
  19. }
  20. /**
  21. * 连接WebSocket
  22. * @param {String} userId 当前用户ID
  23. */
  24. connect(userId) {
  25. if (this.isConnected || !userId) {
  26. return;
  27. }
  28. this.userId = userId;
  29. try {
  30. // uni-app的WebSocket API
  31. this.ws = uni.connectSocket({
  32. url: `${this.wsUrl}?userId=${userId}`,
  33. success: () => {
  34. console.log('🔌 WebSocket连接请求已发送');
  35. },
  36. fail: (err) => {
  37. console.error('❌ WebSocket连接失败:', err);
  38. this.scheduleReconnect();
  39. }
  40. });
  41. // 监听连接打开
  42. uni.onSocketOpen(() => {
  43. console.log('✅ WebSocket已连接');
  44. this.isConnected = true;
  45. this.startHeartbeat();
  46. });
  47. // 监听消息
  48. uni.onSocketMessage((res) => {
  49. this.handleMessage(res.data);
  50. });
  51. // 监听错误
  52. uni.onSocketError((err) => {
  53. console.error('❌ WebSocket错误:', err);
  54. this.isConnected = false;
  55. this.scheduleReconnect();
  56. });
  57. // 监听关闭
  58. uni.onSocketClose(() => {
  59. console.log('🔌 WebSocket已关闭');
  60. this.isConnected = false;
  61. this.stopHeartbeat();
  62. this.scheduleReconnect();
  63. });
  64. } catch (error) {
  65. console.error('❌ WebSocket连接异常:', error);
  66. this.scheduleReconnect();
  67. }
  68. }
  69. /**
  70. * 处理接收到的消息
  71. */
  72. handleMessage(data) {
  73. try {
  74. const message = typeof data === 'string' ? JSON.parse(data) : data;
  75. switch (message.type) {
  76. case 'PONG':
  77. // 心跳响应
  78. console.log('💓 收到心跳响应');
  79. break;
  80. case 'ONLINE':
  81. // 用户上线通知
  82. if (message.fromUserId) {
  83. this.onlineStatusCache.set(String(message.fromUserId), true);
  84. this.notifyStatusChange(String(message.fromUserId), 'online');
  85. }
  86. break;
  87. case 'OFFLINE':
  88. // 用户离线通知
  89. if (message.fromUserId) {
  90. this.onlineStatusCache.set(String(message.fromUserId), false);
  91. this.notifyStatusChange(String(message.fromUserId), 'offline');
  92. }
  93. break;
  94. case 'STATUS_UPDATE':
  95. // 用户状态更新
  96. if (message.userId) {
  97. const status = message.online ? 'online' : 'offline';
  98. this.onlineStatusCache.set(String(message.userId), message.online);
  99. this.notifyStatusChange(String(message.userId), status);
  100. }
  101. break;
  102. default:
  103. // 忽略其他消息类型(如聊天消息等)
  104. break;
  105. }
  106. } catch (error) {
  107. console.error('❌ 消息解析失败:', error);
  108. }
  109. }
  110. /**
  111. * 通过HTTP API查询用户在线状态
  112. * @param {String} userId 目标用户ID
  113. * @return {Promise<Boolean>} 是否在线
  114. */
  115. async queryOnlineStatus(userId) {
  116. try {
  117. const [err, res] = await uni.request({
  118. url: `${this.httpUrl}/checkStatus`,
  119. method: 'GET',
  120. data: {
  121. userId: userId
  122. }
  123. });
  124. if (err) {
  125. console.error('❌ 查询在线状态失败:', err);
  126. return false;
  127. }
  128. if (res.data && res.data.code === 200) {
  129. const isOnline = res.data.data.online || false;
  130. this.onlineStatusCache.set(String(userId), isOnline);
  131. return isOnline;
  132. }
  133. return false;
  134. } catch (error) {
  135. console.error('❌ 查询在线状态异常:', error);
  136. return false;
  137. }
  138. }
  139. /**
  140. * 获取缓存的在线状态
  141. * @param {String} userId 目标用户ID
  142. * @return {Boolean|null} 在线状态,null表示未知
  143. */
  144. getCachedStatus(userId) {
  145. return this.onlineStatusCache.get(String(userId)) || null;
  146. }
  147. /**
  148. * 启动心跳
  149. */
  150. startHeartbeat() {
  151. this.stopHeartbeat();
  152. this.heartbeatTimer = setInterval(() => {
  153. if (this.isConnected) {
  154. this.sendMessage({
  155. type: 'PING',
  156. fromUserId: this.userId,
  157. timestamp: Date.now()
  158. });
  159. }
  160. }, this.heartbeatInterval);
  161. }
  162. /**
  163. * 停止心跳
  164. */
  165. stopHeartbeat() {
  166. if (this.heartbeatTimer) {
  167. clearInterval(this.heartbeatTimer);
  168. this.heartbeatTimer = null;
  169. }
  170. }
  171. /**
  172. * 发送消息
  173. */
  174. sendMessage(data) {
  175. if (!this.isConnected) {
  176. console.warn('⚠️ WebSocket未连接,无法发送消息');
  177. return;
  178. }
  179. try {
  180. uni.sendSocketMessage({
  181. data: JSON.stringify(data),
  182. fail: (err) => {
  183. console.error('❌ 发送消息失败:', err);
  184. }
  185. });
  186. } catch (error) {
  187. console.error('❌ 发送消息异常:', error);
  188. }
  189. }
  190. /**
  191. * 订阅用户状态
  192. * @param {String} targetUserId 目标用户ID
  193. */
  194. subscribeUser(targetUserId) {
  195. if (!this.isConnected || !targetUserId) {
  196. return;
  197. }
  198. this.sendMessage({
  199. type: 'SUBSCRIBE',
  200. fromUserId: this.userId,
  201. toUserId: targetUserId
  202. });
  203. }
  204. /**
  205. * 取消订阅用户状态
  206. * @param {String} targetUserId 目标用户ID
  207. */
  208. unsubscribeUser(targetUserId) {
  209. if (!this.isConnected || !targetUserId) {
  210. return;
  211. }
  212. this.sendMessage({
  213. type: 'UNSUBSCRIBE',
  214. fromUserId: this.userId,
  215. toUserId: targetUserId
  216. });
  217. }
  218. /**
  219. * 监听用户状态变化
  220. * @param {String} targetUserId 目标用户ID
  221. * @param {Function} callback 回调函数 (status) => {}
  222. */
  223. onStatusChange(targetUserId, callback) {
  224. if (!this.statusCallbacks.has(targetUserId)) {
  225. this.statusCallbacks.set(targetUserId, []);
  226. }
  227. this.statusCallbacks.get(targetUserId).push(callback);
  228. // 订阅该用户
  229. this.subscribeUser(targetUserId);
  230. }
  231. /**
  232. * 移除状态监听
  233. * @param {String} targetUserId 目标用户ID
  234. * @param {Function} callback 回调函数
  235. */
  236. offStatusChange(targetUserId, callback) {
  237. if (!this.statusCallbacks.has(targetUserId)) {
  238. return;
  239. }
  240. const callbacks = this.statusCallbacks.get(targetUserId);
  241. const index = callbacks.indexOf(callback);
  242. if (index > -1) {
  243. callbacks.splice(index, 1);
  244. }
  245. // 如果没有回调了,取消订阅
  246. if (callbacks.length === 0) {
  247. this.statusCallbacks.delete(targetUserId);
  248. this.unsubscribeUser(targetUserId);
  249. }
  250. }
  251. /**
  252. * 通知状态变化
  253. */
  254. notifyStatusChange(userId, status) {
  255. console.log(`👤 用户 ${userId} 状态变更: ${status}`);
  256. const callbacks = this.statusCallbacks.get(userId);
  257. if (callbacks && callbacks.length > 0) {
  258. callbacks.forEach(callback => {
  259. try {
  260. callback(status);
  261. } catch (error) {
  262. console.error('❌ 状态回调执行失败:', error);
  263. }
  264. });
  265. }
  266. }
  267. /**
  268. * 计划重连
  269. */
  270. scheduleReconnect() {
  271. if (this.reconnectTimer) {
  272. return;
  273. }
  274. console.log('🔄 将在5秒后重连...');
  275. this.reconnectTimer = setTimeout(() => {
  276. this.reconnectTimer = null;
  277. if (!this.isConnected && this.userId) {
  278. console.log('🔄 尝试重连...');
  279. this.connect(this.userId);
  280. }
  281. }, this.reconnectInterval);
  282. }
  283. /**
  284. * 断开连接
  285. */
  286. disconnect() {
  287. this.stopHeartbeat();
  288. if (this.reconnectTimer) {
  289. clearTimeout(this.reconnectTimer);
  290. this.reconnectTimer = null;
  291. }
  292. if (this.isConnected) {
  293. uni.closeSocket();
  294. this.isConnected = false;
  295. }
  296. this.statusCallbacks.clear();
  297. this.userId = null;
  298. }
  299. /**
  300. * 获取连接状态
  301. */
  302. getConnectionStatus() {
  303. return this.isConnected;
  304. }
  305. }
  306. // 导出单例
  307. export default new PresenceManager();