t***@sino-essence.com
t***@sino-essence.com
  • 发布:2022-06-02 15:37
  • 更新:2023-06-05 01:31
  • 阅读:1066

uni-app的websocket在app中无法关闭,h5中可以关闭,有人知道怎么解决吗?

分类:uni-app

代码如下:

this.theWebsocket = uni.connectSocket({  
          url,  
          success: () => {  
            console.log("websocket连接成功");  
          },  
        });  
  
this.theWebsocket.close({  
          success(res) {  
            _this.theWebsocket = null;  
            _this.centerWeight = "0.00";  
            console.log("关闭成功", res);  
          },  
          fail(err) {  
            console.log("关闭失败", err);  
          },  
        });

app里面close都打印'关闭成功'了,但还是连着的。看了社区里很多帖子,从好几年前到现在都有人报这个问题,一直找不到解决方案。

2022-06-02 15:37 负责人:无 分享
已邀请:
z***@163.com

z***@163.com

直接这样关闭 uni.closeSocket()

t***@sino-essence.com

t***@sino-essence.com (作者)

在renderjs中写html原生的webSocket倒是可以用,也是没有办法的办法了。有人知道正常写法的话麻烦告诉一下。
template:

<view id="weighWs" :prop="weighWsMessage" :change:prop="weighWs.updateWeighWs"></view>

vue的script:

data(){  
  return {  
    weighWsMessage: {}    
  }  
},  
methods:{  
  changeWeight(val) {  
      this.centerWeight = val  
  },  
  connectWs(){  
      // 加个时间戳使得每次都能触发updateWeighWs  
      this.weighWsMessage = {type: 'connectWs', value: 'ws://xxxxxxxx', timeStamp: new Date()}  
  },  
  closeWs(){  
     this.weighWsMessage = {type: 'closeWs', timeStamp: new Date()}  
  }  
}

renderjs:

<script module="weighWs" lang="renderjs">  
// #ifndef H5  
let ws  
export default {  
  mounted() {  
    this.connectWs('ws://192.168.xxxx')  
  },  
  destroyed() {  
    this.closeWs()  
  },  
  methods: {  
    updateWeighWs(newVal) {  
      if (newVal.type === 'closeWs') {  
        this.closeWs()  
      } else if (newVal.type === 'connectWs') {  
        this.connectWs(newVal.value)  
      }  
    },  
    closeWs() {  
      ws.close()  
      ws = null  
    },  
    connectWs(url) {  
      ws && this.closeWs()  
      const _this = this  
      ws = new WebSocket(url);  
  
      ws.onopen = function (evt) {  
        console.log("Connection open ...");  
      };  
  
      ws.onmessage = function (evt) {  
        console.log("Received Message: " + evt.data);  
        _this.$ownerInstance.callMethod('changeWeight', JSON.parse(evt.data).value)  
      };  
  
      ws.onclose = function (evt) {  
        console.log("Connection closed.");  
      };  
    }  
  }  
}  
// #endif  
</script>
1***@qq.com

1***@qq.com

close里的参数有一个code,1000表示正确。默认是1000.随便用一个其它值,看下行不行,我感觉好像可以:

uni.closeSocket({
code: 500
})

要回复问题请先登录注册