我试图发送和接收UDP广播消息。
一开始它没有用,但在我发现我必须在接收器端使用通配符地址(0.0.0.0)之后。所以它奏效了。
但我想了解为什么我必须使用通配符地址?它绑定到所有网络接口,是不是有办法绑定到特定地址并仍然继续接收广播?
发件人
InetAddress localHOst = InetAddress.getByName("192.168.1.1");
DatagramSocket socket = new DatagramSocket(50000, localHost);
socket.setBroadcast(true);
byte[] data = msg.getBytes();
InetAddress dest = InetAddress.getByName("192.168.255.255");
DatagramPacket packet = new DatagramPacket(data, data.length, dest, 49152);
socket.send(packet);
socket.close();
接收机
InetAddress broadcastWildcard = InetAddress.getByName("0.0.0.0");
DatagramSocket socket = new DatagramSocket(49152, broadcastWildcard);
byte[] data = null;
while(true) {
data = new byte[Settings.MSG_SIZE];
DatagramPacket packet = new DatagramPacket(data, data.length);
socket.receive(packet);
}