【uni-app】websocket在vue的基本使用


前后端需要使用websocket连接来进行传值,但是手机端和APP端的websocket方法使用是不一致的,需要进行区分。

创建websocket连接

进入页面的时候创建websocket连接,整个页面随时可用,整个websocket可以放在进度条或者是导航栏,我这来是放在了时间进度条里面,每个页面都可以调用。

这个方法是在created的方法中调用的,后续其他关于websocket的方法都在这个方法中写。

   connectSocketInit() {}

链接websocket

创建一个websocket对象,用来发送,接收和关闭socket,用这个对象来连接服务器

this.socketTask = uni.connectSocket({
        // 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
        url: config.socketBaseUrl,//后端websocket地址
        success(data) {
          console.log("websocket连接成功");
        },
      });

打开websocket链接,

只有打开websocket链接才可以发消息和接收消息

this.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...!");
					this.is_open_socket = true;

发送消息

this.socketTask.send({
	data:{
		"classId":this.localStorage.get("classId"),
		"courseId":this.localStorage.get("courseId")
	},
	async success() {
		console.log("消息发送成功");
	},
});

接收消息

this.socketTask.onMessage((res) => {
	console.log("收到服务器内容:" + res.data);
});

事件监听,关闭socket

// 这里仅是事件监听【如果socket关闭了会执行】
this.socketTask.onClose(() => {
	console.log("已经被关闭了");
});

关闭websocket

这个方法在页面离开的时候执行

    // 关闭websocket【离开这个页面的时候执行关闭】
    closeSocket() {
      this.socketTask.close({
        success(res) {
          this.is_open_socket = false;
          console.log("关闭成功", res);
        },
        fail(err) {
          console.log("关闭失败", err);
        },
      });
    },

点击事件调用websocket

    clickRequest() {
    //要确保当前已经打开了websocket链接
      if (this.is_open_socket) {
        //数据发送
        //获取数据
        var classId = localStorage.getItem("classId");
        var courserId = localStorage.getItem("courseId");
        this.type = "approve";
        //拼接后端接收的字符串
        let actions ="type:" +this.type + "," +"classId:" +classId +",courserId:" +courserId;
        this.socketTask.send({
          data: actions,
          async success() {
            console.log("消息发送成功");
          },
        });
      }
    },

全部代码

  // 进入这个页面的时候创建websocket连接【整个页面随时使用】
    connectSocketInit() {
      // 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
      this.socketTask = uni.connectSocket({
        // 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
        url: config.socketBaseUrl,
        success(data) {
          console.log("websocket连接成功");
        },
      });

      // 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
      this.socketTask.onOpen((res) => {
        console.log("WebSocket连接正常打开中...!");
        this.is_open_socket = true;

        // 注:只有连接正常打开中 ,才能正常成功发送消息
       
        this.socketTask.send({
        	data:{
        		"classId":this.localStorage.get("classId"),
        		"courseId":this.localStorage.get("courseId")
        	},
        	async success() {
	        	console.log("消息发送成功");
	        },
        });

        // 注:只有连接正常打开中 ,才能正常收到消息
        this.socketTask.onMessage((res) => {
          //数据接收
          this.redata = res.data;
          if (this.redata.indexOf("suspend") != -1) {
            var array = this.redata.split(",");
            var activeId = array[5];
            var activeId1 = activeId.split(":")[1];
            var activityId = localStorage.getItem("activityId");
            if (this.redata.match("type:suspend") && activeId1 == activityId) {
              this.num = this.num + 1;
              this.$refs.uToast.show({
                title: "请注意,当前有 " + this.num + " 名学生申请暂停课程",
                type: "success",
                position: "top",
              });
            }
          }
        });
      });
      // 这里仅是事件监听【如果socket关闭了会执行】
      this.socketTask.onClose(() => {
        console.log("已经被关闭了");
      });
    },
    // 关闭websocket【离开这个页面的时候执行关闭】
    closeSocket() {
      this.socketTask.close({
        success(res) {
          this.is_open_socket = false;
          console.log("关闭成功", res);
        },
        fail(err) {
          console.log("关闭失败", err);
        },
      });
    },
  
    clickRequest() {
      if (this.is_open_socket) {
        //数据发送
        //获取数据
        var classId = localStorage.getItem("classId");
        var courserId = localStorage.getItem("courseId");
        this.type = "approve";
        //拼接后端接收的字符串
        let actions ="type:" +this.type + "," +"classId:" +classId +",courserId:" +courserId;
        this.socketTask.send({
          data: actions,
          async success() {
            console.log("消息发送成功");
          },
        });
      }
    },

这里只介绍了websocket在APP端应用的代码,下一篇介绍一下websocket服务端的代码。点击直达

评论 43
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张_Laura

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值