收藏
回答

小程序UDP通信开发者工具正常使用,真机和预览都不行是什么原因啊?

Page({
  data: {
    udpSocket''
  },

  sendMessage() {
    let ip = '192.168.3.255'
    let port = 888
    let message = 'hello i am wechat'

    this.data.udpSocket.send({
      address: ip,
      port: port,
      message: message
    })
  },

  initUdpSocket() {
    this.data.udpSocket = wx.createUDPSocket();
    if (this.data.udpSocket === null) {
      console.log('暂不支持')
      return;
    }

    this.data.udpSocket.onListening(function (res{
      console.log('监听中Res ===' + res)
    })

    const locationPort = this.data.udpSocket.bind(888)
    this.setData({
      'locationUrl.port': locationPort
    })

    this.data.udpSocket.onMessage(function (res{
      console.log('remoteInfo ===' + res.remoteInfo)
      console.log('remoteInfo.size ===' + res.remoteInfo.size)
      if (res.remoteInfo.size > 0) {
        console.log('UDP接收数据 ' + res.remoteInfo.size + ' 字节:' + JSON.stringify(res, null'\t'))


        let unit8Arr = new Uint8Array(res.message);
        let encodedString = String.fromCharCode.apply(null, unit8Arr);
        let escStr = escape(encodedString);
        let decodedString = decodeURIComponent(escStr);

        console.log('str===' + decodedString)
        wx.showModal({
          title'提示',
          content: decodedString,
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })
  },

  lxt :function(){
    this.initUdpSocket()
    this.sendMessage()
  },

})

上面的代码开发者工具中可以接收也可以发送,用预览、真机调试、体验版都不能发送和接收。请问是什么原因啊?

谢谢!

回答关注问题邀请回答
收藏

2 个回答

  • 社区技术运营专员--阳光
    社区技术运营专员--阳光
    2021-12-08

    请具体描述问题出现的流程,并提供能复现问题的简单代码片段(https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html)。

    2021-12-08
    有用
    回复 8
    • 盛.
      盛.
      2021-12-08
      https://developers.weixin.qq.com/s/MLSLuomq7Dvq
      该代码点击按钮会发送一条UDP消息,用微信开发工具网络调试助手能接收到消息,网络调试助手发送UDP消息微信开发工具也能收到。但是用预览和真机调试就不行了,不能发送也不能接收,社区里相关方法已经都试了,没解决。谢谢!
      2021-12-08
      回复
    • 李汉三
      李汉三
      2022-01-07回复盛.
      bind改为随机,bind()
      2022-01-07
      回复
    • 进无止境
      进无止境
      2022-02-15
      关键做的功能是监听固定端口发的消息,随机端口就接收不到消息
      2022-02-15
      回复
    • 社区技术运营专员--阳光
      社区技术运营专员--阳光
      2022-02-22回复盛.
      你好,具体有什么报错信息吗,可以通过 UDPSocket.onError 监听错误事件
      2022-02-22
      回复
    • 社区技术运营专员--阳光
      社区技术运营专员--阳光
      2022-02-22回复进无止境
      你好,具体有什么报错信息吗,可以通过 UDPSocket.onError 监听错误事件
      2022-02-22
      回复
    查看更多(3)
  • 进无止境
    进无止境
    2022-02-15

    我也遇到同样问题,开发者工具上可以正常接收,真机预览就不行,显示的端口第一次可以,过后重新进入小程序就变为0了,

    调了close方法还是没用,真机调试模式,打印的端口直接undefined的,微信的东西bug太多了,又没人解决

    2022-02-15
    有用
    回复
登录 后发表内容