uniapp的websoket的api使用方法

websoket() {
                console.log('初始化');
                uni.connectSocket({
                    url: 'ws://192.168.1.111:19107/hand',
                })
                uni.onSocketOpen(function(res) {
                    uni.$u.toast('WebSocket连接已打开!')
                });
                uni.onSocketError(function(res) {
                    uni.$u.toast('WebSocket连接打开失败,请检查!')
                });
            },
            jiexiaoxi() {
                console.log('收到的消息');
                    uni.onSocketMessage(function(res) {
                    console.log('收到服务器内容:' + res.data);
                })
            },
            async fasong() {
                const params={
                    receiveUserid:'e68b0d11d077a4929f0333dd87f67c7e',
                    message:'测试'
                }
                const arr=await http.post('/api/chat/chatAdd',params)
                console.log(arr);
            },
            shoucilianjie() {
                setTimeout(()=>{
                    const data = {
                    "action": "init",
                    "chatMsg": {
                        "senderId": 'e68b0d11d077a4929f0333dd87f67c7e',
                        "receiverId": "",
                        "msg": ""
                    }
                }
                const msg = JSON.stringify(data)
                console.log('登录发送');
                uni.sendSocketMessage({
                    data: msg,
                    success:(res)=>{console.log(res)}
                });
                },100)
                
            },
            xintiao() {
                setInterval(()=>{
                    const data = {
                        action: 'heartbeat'
                    }
                    const msg = JSON.stringify(data)
                    console.log('心跳');
                    uni.sendSocketMessage({
                        data: msg,
                        success:(res)=>{console.log(res)}
                    });
                },10000)
                    
            },

执行顺序

 this.websoket()先建立链接
 this.shoucilianjie()建立后验证身份
 this.xintiao()身份验证完毕后建立心跳

 this.jiexiaoxi()最后接收消息

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值