HarmonyOS 真机运行socket.UDPSocket.send 报没有权限,但是ability这边已经配置了网络权限?

操作步骤:

1、入口模块配置权限如下:

"requestPermissions": [
  {
    "name": "ohos.permission.INTERNET",
    "reason": "$string:internet_reason",
    "usedScene": {
      "abilities": [
        "EntryAbility"
      ],
      "when": "inuse"
    }
  },
  {
    "name": "ohos.permission.GET_NETWORK_INFO",
    "reason": "$string:network_reason",
    "usedScene": {
      "abilities": [
        "EntryAbility"
      ],
      "when": "inuse"
    }
  }
]

2、并在自建feature下面的一个子模块引用common下的connection模块,发送广播步骤如下:

a. 先绑定,并且返回成功:

const udp = socket.constructUDPSocketInstance()
udp.bind({
  address: '0.0.0.0'
}

b. 然后发广播失败:

const address: socket.NetAddress = {
  address: "192.168.1.255",
  port: 9010
}

const sendOptions: socket.UDPSendOptions = {
  data: "discover mote._tcp 9010",
  address: address
}

udp.send(sendOptions, (err: BusinessError) => {
  if (err) {
    // 来到这里,报无权限
    Logger.error(`send fail: ${err.message}`);
    return;
  }
}
阅读 435
1 个回答

权限添加:

"reqPermissions": [
  {
    "name": "ohos.permission.GET_NETWORK_INFO"
  },
  {
    "name": "ohos.permission.SET_NETWORK_INFO"
  },
  {
    "name": "ohos.permission.INTERNET"
  }
],

udp做发送端bind本机ip 192.168.xx.xx端口为0系统自动分配。this.udp.bind({ address: ‘0.0.0.0’, port: 0 }),udp做广播接收端时bind 0.0.0.0 显示指定端口如8080用于发送端send给8080。打开广播选项send192.168.xx.255 8080。

logo
HarmonyOS
子站问答
访问
宣传栏