MulticastSocket 接收消息两次

MulticastSocket receives message twice

我通过 MulticastSocket 向 WIFI 接入点发送消息,并且总是收到两次回复。如果我尝试向自己发送消息,我会再次收到消息两次。这是我的接收者代码:

protected Void doInBackground(Void... params) {

                String lText;
                byte[] lMsg = new byte[GlobalConfig.MAX_UDP_DATAGRAM_LEN];
                DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);
                MulticastSocket ds = null;
                try {
                    ds = new MulticastSocket (32001);
                    InetAddress serverAddr = InetAddress.getByName("224.237.124.120");
                    ds.joinGroup(serverAddr);
                    while (serverActive) {

                        ds.receive(dp);
                        Log.d("UDP packet received", dp.toString());
                        lText = new String(lMsg, 0, dp.getLength());
                        receivedMessage = lText;
                        doSomething();

                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (ds != null) {
                        ds.close();
                    }
                }
                return null;
            }

我尝试通过 DatagramSocket 和 MulticastSocket 发送 - 无论如何。我总是收到两次消息。我不明白为什么!

编辑:我的 LogCat:

I/GatewayController﹕ Message Sent
...

D/UDP packet received﹕ java.net.DatagramPacket@422dc860
D/UDP packet received﹕ java.net.DatagramPacket@422dc860

EDIT2:发件人代码

protected Void doInBackground(Void... params) {

                DatagramSocket ds = null;
                try {
                    ds = new DatagramSocket();
                    InetAddress serverAddr = InetAddress.getByName("224.237.124.120");
                    DatagramPacket dp;
                    dp = new DatagramPacket(byteMsg, byteMsg.length,
                            serverAddr, 32000);
                    ds.send(dp);

正确的方法是:

InetAddress group = InetAddress.getByName(GlobalConfig.MULTICAST_IP);
SocketAddress sockaddr = new InetSocketAddress(group,GlobalConfig.LOCAL_PORT);
ds = new MulticastSocket(sockaddr);
ds.joinGroup(group);

这很重要,但在 Internet 的示例中很难找到:

SocketAddress sockaddr = new InetSocketAddress(group,GlobalConfig.LOCAL_PORT);
ds = new MulticastSocket(sockaddr);

I tried to send via DatagramSocket and via MulticastSocket - no matter. I get messages alway twice. I don't understand why!

EDIT: my LogCat:

I/GatewayController﹕ Message Sent ...
D/UDP packet received﹕ java.net.DatagramPacket@422dc860 D/UDP packet received﹕ java.net.DatagramPacket@422dc860

这不能证明您收到了两次相同的消息。这证明您总是接收到相同的字节数组。尝试记录消息 content.

但是组播是 UDP,UDP 不保证传送,不保证单次传送,也不保证顺序传送,因此您仍然有可能得到重复的。如果这在语义上很重要,您需要通过序列号来检测它。