123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142 |
- class WebSocketManager {
- constructor(userId) {
- // 1用户 2志愿者
- this.system = uni.getStorageSync('userType') === 1 ? '1' : '2';
- this.userId = userId;
- this.url = `ws://192.168.100.127:9527/websocket/${this.system}/${this.userId}`;
- this.socketTask = null;
- this.heartbeatInterval = null;
- this.reconnectTimer = null;
- this.isConnecting = false;
- this.onMessageCallback = null;
- }
- /**
- * 建立连接
- */
- connect() {
- if (this.isConnecting || !this.userId) {
- console.warn('正在连接或缺少用户ID');
- return;
- }
- this.isConnecting = true;
- console.log('建立 WebSocket 连接:', this.url);
- if(!this.socketTask){
- this.socketTask = uni.connectSocket({
- url: this.url,
- success: () => console.log('WebSocket 连接创建成功'),
- });
- }
-
- this._setupEventListeners();
- }
- /**
- * 设置事件监听器
- */
- _setupEventListeners() {
- this.socketTask.onOpen(() => {
- console.log('WebSocket 已打开');
- this.isConnecting = false;
- this.startHeartbeat();
- });
- this.socketTask.onMessage(res => {
- console.log('收到 WebSocket 消息:', res.data);
- try {
- const data = JSON.parse(res.data);
- if (typeof this.onMessageCallback === 'function') {
- this.onMessageCallback(data); // 回调通知外部
- }
- } catch (e) {
- console.error('消息解析失败:', res.data);
- }
- });
- this.socketTask.onError(err => {
- console.error('WebSocket 发生错误:', err);
- });
- this.socketTask.onClose(() => {
- console.log('WebSocket 已关闭');
- this.stopHeartbeat();
- this.reconnect(); // 自动重连
- });
- }
- /**
- * 启动心跳机制
- */
- startHeartbeat() {
- // this.stopHeartbeat();
- // this.heartbeatInterval = setInterval(() => {
- // uni.sendSocketMessage({
- // data: 'heartbeat',
- // success: () => console.log('心跳包已发送'),
- // fail: err => {
- // console.error('心跳包发送失败:', err);
- // this.stopHeartbeat();
- // }
- // });
- // }, 5000);
- }
- /**
- * 停止心跳机制
- */
- stopHeartbeat() {
- if (this.heartbeatInterval) {
- clearInterval(this.heartbeatInterval);
- this.heartbeatInterval = null;
- }
- }
- /**
- * 重新连接
- */
- reconnect() {
- clearTimeout(this.reconnectTimer);
- this.reconnectTimer = setTimeout(() => {
- console.log('尝试重新连接...');
- this.connect();
- }, 3000);
- }
- /**
- * 主动发送消息
- */
- sendMessage(message) {
- if (this.socketTask && typeof message !== 'undefined') {
- uni.sendSocketMessage({
- data: typeof message === 'object' ? JSON.stringify(message) : message,
- success: () => console.log('消息发送成功:', message),
- fail: err => console.error('消息发送失败:', err)
- });
- } else {
- console.warn('尚未建立连接,消息发送失败');
- }
- }
- /**
- * 主动关闭连接
- */
- closeConnection() {
- if (this.socketTask) {
- this.socketTask.close();
- this.socketTask = null;
- }
- this.stopHeartbeat();
- }
- /**
- * 设置消息回调
- */
- onMessage(callback) {
- this.onMessageCallback = callback;
- }
- }
- export default WebSocketManager;
|