使用多播在udp中复制数据包

时间:2018-01-21 12:09:54

标签: java udp multicast

这是我的问题: 在下面的示例中,我收到重复的数据包,但仅在我的网络中,我不明白为什么。有趣的是,这只发生在我的网络上,我已经尝试过其他4个网络,一切正常。我使用Wireshark跟踪数据包,它显示了双包。

以下是代码:

服务器:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class ProvaServer {
    public static void main(String[] args) {
        try (DatagramSocket socket = new DatagramSocket(12000)) {
            InetAddress address = InetAddress.getByName("224.0.3.5");
            Integer i = 1;
            while (true) {
                DatagramPacket msgPacket = new DatagramPacket(i.toString().getBytes(), i.toString().getBytes().length, address, 11000);
                socket.send(msgPacket);
                i++;
                Thread.sleep(2000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

客户端:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class ProvaClient {
    public static void main(String [] args) {

        try (MulticastSocket mcs = new MulticastSocket(11000)){
            mcs.setReuseAddress(true);
            InetAddress address = InetAddress.getByName("224.0.3.5");
            mcs.joinGroup(address);
            while (true) {
                byte[] buf = new byte[1024];
                DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
                mcs.receive(msgPacket);
                String byteToString = new String(msgPacket.getData(),0, msgPacket.getLength(), "US-ASCII");
                System.out.println("Messaggio ricevuto: " + byteToString);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

输出:

Messaggio ricevuto: 1
Messaggio ricevuto: 2
Messaggio ricevuto: 3
Messaggio ricevuto: 4
Messaggio ricevuto: 4
Messaggio ricevuto: 5
Messaggio ricevuto: 5

0 个答案:

没有答案