DatagramSocket可以接收多播数据包吗 [英] Can DatagramSocket Receive multicast Packets
问题描述
我有一个在线程中运行的代码,用于将DatagramPacket发送到计算机中每个NetworkInterface的广播地址以及多播组.如下:
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. 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();}
我的问题是:我可以使用相同的DatagramSocket接收(组播和广播)数据包吗?请注意,两者都发送到同一端口.我应该在37486端口上打开MulticastSocket还是DatagramSocket来接收两个数据包吗?
My question is: Can i receive both (multicast and broadcast) packets using same 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?
(数据包是从PC发送的,但在Android上已接收)
推荐答案
DatagramSocket
是否可以接收多播数据包
Can
DatagramSocket
receive multicast Packets
否,因为它无法加入多播组.
No, because it can't join the multicast group.
您没有要求,但是为了完整性:
You didn't ask, but for completeness:
DatagramSocket
是否可以发送多播数据包
Can
DatagramSocket
send multicast Packets
是的
MulticastSocket
可以接收数据报(非多播)数据包
Can
MulticastSocket
receive datagram (non-multicast) packets
是的
这篇关于DatagramSocket可以接收多播数据包吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!