2019-07-08 遇到的一点小问题
最近做局域网内Android端发UDP广播出去,然后接收服务器返回的信息。
参考的文章 Android UDP 广播实践,要用的都有写。
private final static String BROADCAST_IP = "255.255.255.255"; //广播范围
private final static int BROADCAST_PORT = 8888; //端口
DatagramSocket socket = new DatagramSocket(BROADCAST_PORT);
发送
byte[] sendBuf = 发送内容.getBytes();
InetAddress address = InetAddress.getByName(BROADCAST_IP);
DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, address, BROADCAST_PORT);
socket.send(sendPacket);
socket.setBroadcast(true);
接收
byte[] ackBuf = new byte[1024];
InetAddress address = InetAddress.getByName(BROADCAST_IP);
DatagramPacket ackPacket = new DatagramPacket(ackBuf, ackBuf.length, address, BROADCAST_PORT);
socket.receive(ackPacket);
接收内容 = new String(ackPacket.getData(), 0, ackPacket.getLength());
应答的IP = ackPacket.getAddress().getHostAddress();
能收到udp消息,但有可能出现不在同一个广播地址,无法http沟通的情况,所以顺便查了下当前设备的广播地址,和服务器的比对。
/**
* 获取当前移动设备的广播地址
* 返回示例:192.168.11.255
*/
private String getPhoneBroadcast() throws SocketException {
System.setProperty("java.net.preferIPv4Stack", "true");
for (Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces(); niEnum.hasMoreElements(); ) {
NetworkInterface ni = niEnum.nextElement();
if (!ni.isLoopback()) {
for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
if (interfaceAddress.getBroadcast() != null) {
return interfaceAddress.getBroadcast().toString().substring(1);
}
}
}
}
return null;
}
网友评论