简体   繁体   English

DatagramSocket可以接收多播数据包吗

[英]Can DatagramSocket Receive multicast Packets

I have a code that runs in a thread, which i use to send a DatagramPacket to broadcast address of each NetworkInterface in the computer and also to a multicast group. 我有一个在线程中运行的代码,用于将DatagramPacket发送到计算机中每个NetworkInterface的广播地址以及多播组。 It is as follows: 如下:

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();}

My question is: Can i receive both (multicast and broadcast) packets using same DatagramSocket? 我的问题是:我可以使用相同的DatagramSocket接收(多播和广播)数据包吗? Note that both are sent to same port. 请注意,两者都发送到同一端口。 Should i open a MulticastSocket or a DatagramSocket at the port 37486 to receive both packets? 我应该在37486端口上打开MulticastSocket还是DatagramSocket来接收两个数据包吗?

(Packets are send from PC but received on Android) (数据包从PC发送,但在Android上接收)

Can DatagramSocket receive multicast Packets DatagramSocket可以接收多播数据包吗

No, because it can't join the multicast group. 不可以,因为它无法加入多播组。

You didn't ask, but for completeness: 您没有要求,但出于完整性考虑:

Can DatagramSocket send multicast Packets DatagramSocket可以发送多播数据包吗

Yes. 是。

Can MulticastSocket receive datagram (non-multicast) packets MulticastSocket可以接收数据报(非多播)数据包吗

Yes. 是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM