uni-app中使用websocket

1.data中声明websocket

 data() {
    return {
      websocket:null,
    };
  },

2.created函数中调用

 created() {
    this.initWebsocket();
  },

3.创建websocket连接进行通信

 initWebsocket() {
     let that = this
      that.$api.baseUrl = that.$api.baseUrl
        ? that.$api.baseUrl
        : window.location.origin;
      let tempUrl = that.$api.baseUrl.substr(that.$api.baseUrl.indexOf("//"));
      let storeId = that.user.storeId;
      let url = "";
    // 如果协议是https使用wss,http使用ws
      if (that.$api.baseUrl.indexOf("https") != -1) {
        url = `wss:${tempUrl}/pgApi/v1/websocket/poolRemain?storeId=${storeId}&userId=${that.user.id}`;
      } else {
        url = `ws:${tempUrl}/pgApi/v1/websocket/poolRemain?storeId=${storeId}&userId=${that.user.id}`;
      }
 // 创建websocket
      that.websocket= uni.connectSocket({
        url: url, 
        success(data) {
          console.log("websocket连接成功");
        },
      });
// 建立websocket连接
      that.websocket.onOpen((res) => {
        console.log("WebSocket连接正常打开中...!");
        // 注:只有连接正常打开中 ,才能正常成功发送消息
        that.websocket.send({
          data: "uni-app发送一条消息",
          async success() {
            console.log("消息发送成功");
          },
        });
        // 注:只有连接正常打开中 ,才能正常收到消息
        that.websocket.onMessage((res) => {
          console.log("收到服务器内容:" + res.data);
          this.getCouponList();
        });
      });
      // 监听webscket关闭的事件
      that.websocket.onClose(() => {
        console.log("已经被关闭了");
      });
   // 监听发生错误时的时间
    that.websocket.onError(() => {
        console.log('websocket连接失败');
       })
    },

你可能感兴趣的:(uni-app中使用websocket)