//引入需要用到的安卓包
let DatagramPacket = plus.android.importClass('java.net.DatagramPacket'); //udp接收信息引用的java类
let DatagramSocket = plus.android.importClass('java.net.DatagramSocket'); //udp创建udp引用java类
let InetAddress = plus.android.importClass('java.net.InetAddress'); //绑定ip引用java类
let NetworkInterface = plus.android.importClass('java.net.NetworkInterface'); //获取主机ip
let JString = plus.android.importClass('java.lang.String'); //字符串转换类
let port = that.port; //广播端口
let getPort = that.getPort; //本机端口
let timeout = 5000; //超时时间
let address = that.ip;
let getData = [];
try {
if (DatagramSocket == undefined) {
return;
}
let ip = InetAddress.getByName(address);
// 绑定本机接收UDP反馈消息的端口号
that.socket = new DatagramSocket(getPort);
// 设置接收超时时长
that.socket.setSoTimeout(timeout);
// 接收数据
let isReceive = true;
while (isReceive) {
try {
// 设置接收缓存,需要用0填充,否则为 null 无法接收。
let buffer = new Array(1024).fill(0);
let packet = new DatagramPacket(buffer, buffer.length);
that.socket.receive(packet);
let data = new JString(packet.getData()).trim();
if (data.length == 0) {
// 接收超时,结束接收
isReceive = false;
} else {
console.log('=====收到数据======', data);
getData.push(data)
}
} catch (ex) {
that.socket.close();
isReceive = false;
console.log('接收数据失败:' + ex)
}
}
} catch (ex) {
console.log('========出错了=======', ex);
} finally {
if (that.socket != undefined) {
that.socket.close();
}
}
2***@qq.com
- 发布:2022-09-23 13:06
- 更新:2023-05-23 15:36
- 阅读:384
1 个回复
wangcheng94
请问解决了吗?