DatagramSocket可以接收多播数据包

时间:2016-10-24 02:35:03

标签: java android udp broadcast multicast

我有一个在线程中运行的代码,我用它将DatagramPacket发送到计算机中每个NetworkInterface的广播地址,也发送到多播组。它如下:

try {
    String decl="Mymessage";
    DatagramPacket ackdp;
    while(true)
        {
        Thread.sleep(3000);
        //First sending multicast (not broadcast) packet to a multicast group
        //231.26.179.75:37486
        ackdp=new DatagramPacket(s.getBytes(),s.length(),multicastGroup,port);
        BroadcastSocket.send(ackdp);
        //Now sending same message to broadcast address of each of the n/w interfaces
        Enumeration nwInterfaces = NetworkInterface.getNetworkInterfaces();
        while(nwInterfaces.hasMoreElements())
                {
                NetworkInterface ni=(NetworkInterface) nwInterfaces.nextElement();
                if(ni.isLoopback()||!ni.isUp())
                        continue;
                for(InterfaceAddress ifa:ni.getInterfaceAddresses())
                        {
                        InetAddress broadcastIP=ifa.getBroadcast();
                        if(broadcastIP==null)
                                continue;
                        ackdp=new DatagramPacket(s.getBytes(),s.length(),broadcastIP,port);
                        BroadcastSocket.send(ackdp);
                        //port is same here :37486 (ip varies with network interface)
                        }
                }
        }
    } catch (Exception ex) {ex.printStackTrace();}

我的问题是:我可以使用相同的DatagramSocket接收(多播和广播)数据包吗?请注意,两者都发送到同一端口。我应该在端口37486打开MulticastSocket还是DatagramSocket来接收这两个数据包?

(数据包是从PC发送但在Android上收到的)

1 个答案:

答案 0 :(得分:2)

  

DatagramSocket可以接收多播数据包

不,因为它无法加入多播组。

你没有问,但为了完整性:

  

DatagramSocket可以发送多播数据包

  

MulticastSocket可以接收数据报(非多播)数据包