操作步骤:
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;
}
}
权限添加:
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。