1.AndroidManifest.xml文件中添加网络权限
public static List<String> adds = new ArrayList<>();
public static void resetAdds() {
adds.clear();
try {
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
if (enumeration != null) {
while (enumeration.hasMoreElements()) {
NetworkInterface wf = enumeration.nextElement();
Enumeration<InetAddress> ei = wf.getInetAddresses();
if (ei != null) {
while (ei.hasMoreElements()) {
InetAddress ia = ei.nextElement();
if (!ia.isLoopbackAddress()) {
String address = ia.getHostAddress();
if (address != null && address.indexOf(":") == -1) {
for (int i = address.length() - 2; i >= 0; i--) {
if (address.charAt(i) == '.') {
adds.add(address.substring(0, i) + ".255");
break;
}
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
3.用线程发送udp广播
public static void udpSend(byte[] data) {
new Thread() {
@Override
public void run() {
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
for (int i = 0; i < UdpSendService.adds.size(); i++) {
DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName(UdpSendService.adds.get(i)), UdpSendService.portNumber);
socket.send(packet);
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null) {
socket.close();
}
}
}
}.start();
}
4.用线程接收udp广播
public static void udpReceive() {
for (int i = 0; i < adds.size(); i ++) {
int finalI = i;
new Thread() {
@Override
public void run() {
DatagramSocket socket = null;
try {
socket = new DatagramSocket(portNumber, InetAddress.getByName(adds.get(finalI)));
byte[] buffer = new byte[4096];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
socket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
Log.d("test_udp_receive", "result:" + message);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null) {
socket.close();
}
}
}
}.start();
}
}
到此这篇udp广播报文(udp 广播)的文章就介绍到这了,更多相关内容请继续浏览下面的相关推荐文章,希望大家都能在编程的领域有一番成就!版权声明:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权、违法违规、事实不符,请将相关资料发送至xkadmin@xkablog.com进行投诉反馈,一经查实,立即处理!
转载请注明出处,原文链接:https://www.xkablog.com/bcyy/81396.html