微信小程序使用websokcet

2024-11-28 16:53:28 阅读:4 编辑

app.js

  1. onLaunch调用this.handleWebsocket()
  2. globalData设置初始化值websocket_connect_status=0

    handleWebsocket() {
    this.initWebsocketConnection();
    this.reconnectWebsocketInterval();
    },
    reconnectWebsocketInterval() {
    let timer = setInterval(() => {
      if (this.globalData.websocket_connect_status == 0) {
        console.log("websocket重连中...");
        this.initWebsocketConnection()
      }
    }, 2000);
    },
    getWebocketUserId() {
    let user_id = 0;
    let zhyshopInfo = wx.getStorageSync('zhyshopInfo');
    if (zhyshopInfo) {
      user_id = zhyshopInfo.id;
    }
    if (user_id) {
      let type = "mp";
      if (this.app_type == "wechat") {
        if (this.siteInfo.platform == "h5") {
          type = "h5";
        } else {
          type = "wechat";
        }
      } else {
        if (this.globalData.is_new_app) {
          type = this.globalData.new_app_type;
        }
      }
      return user_id + "_" + type;
    } else {
      return false;
    }
    
    },
    bindWebsocketUser() {
    let user_id = this.getWebocketUserId();
    if (user_id) {
      let message = {
        tag: "__bind_user",
        data: {
          user_id: user_id,
        }
      };
      message = JSON.stringify(message);
      wx.sendSocketMessage({
        data: message
      });
    }
    
    },
    initWebsocketConnection() {
    let enable = true;
    if(!enable){
      return;
    }
    const url = 'wss://ai.zhyai.cn:8282'
    let socket = wx.connectSocket({
      url: url,
      success: function (res) {
    
      }
    })
    
    socket.onOpen(() => {
      this.globalData.websocket_connect_status = 1;
      console.log("websocket连接成功");
    
    });
    socket.onError((error) => {
      console.log(`WebSocket error:`, error)
    });
    socket.onClose((e) => {
      console.log(`server close`, e.code, e.reason);
      socket.close({
        code: 1000
      });
      this.globalData.websocket_connect_status = 0;
    });
    socket.onMessage((e) => {
      console.log(e.data);
    });
    
    },