我正在开发一个聊天应用程序,Android 客户端将使用多播(UDP)交换他们的 IP。
每台设备都会在一个单独的线程中将其 ip 发送到多个客户端(运行此应用程序的所有设备)。将有另一个接收者线程来监听这些多播数据包。这是我的代码。
//多播代码。
DatagramSocket socket = new DatagramSocket(9898);
byte buff[] = ip.getBytes();
DatagramPacket packet = new DatagramPacket(buff, buff.length, InetAddress.getByName("224.0.0.1"),9999);
socket.send(packet);
socket.close();
//接收代码
MulticastSocket socket = new MulticastSocket(9999);
InetAddress group = InetAddress.getByName("224.0.0.1");
socket.joinGroup(group);
DatagramPacket packet;
byte[] buf = new byte[256];
byte b = 'x'; //just a separator for time being
Arrays.fill(buf,b);
packet = new DatagramPacket(buf, buf.length);
String received= "";
while(received!=null)
{
socket.receive(packet);
received = new String(packet.getData());
received = received.substring(0,received.indexOf('x'));
this.setIp(received);
System.out.println("Address: " + received);
}
socket.leaveGroup(group);
socket.close();
问题是每个设备都打印自己的地址。似乎它从不听其他多播包(我的意思是它也应该打印其他 ip)。我也得到一个下面的日志,不确定这是否相关。
11-04 23:56:17.985: I/OSNetworkSystem(603): mcastAddDropMembership interfaceIndex=0
任何帮助将不胜感激。