多播ping回到我的客户端

时间:2011-06-12 22:51:53

标签: android multicast

所以我发送一个组播数据包来发现任何可用的服务,我得到的第一个回复就是我首先发送的消息。

// create socket
InetAddress addr = InetAddress.getByName(host);
MulticastSocket socket = new MulticastSocket(port);
socket.joinGroup(addr);

// send ping
byte[] byteArray = PING.getBytes();
DatagramPacket packet =
            new DatagramPacket(byteArray, byteArray.length, addr, port);
socket.send(packet, (byte) 255);

// listen for pong
byteArray = PONG.getBytes();
packet = new DatagramPacket(byteArray, byteArray.length);
socket.setSoTimeout(2000);
socket.receive(packet); // TODO: first message is echo from me!!!
socket.receive(packet);
String response = new String(packet.getData());
Toast toast = Toast.makeText(context, "Received '" + response +
            "' from " + packet.getAddress(), Toast.LENGTH_LONG);
toast.show();

如何阻止这种情况发生?

1 个答案:

答案 0 :(得分:3)

您想要设置多播套接字环回模式:

socket.setLoopbackMode(true); // Amusingly, this parameter is a disable

More info可以在Android网站上找到。