Broadcasting and Multicasting in Java – Java中的广播和组播

最后修改: 2017年 8月 15日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

In this article, we describe how one-to-all (Broadcast) and one-to-many (Multicast) communications can be handled in Java. The broadcast and multicast concepts outlined in this article are based on the UDP protocol.

在这篇文章中,我们将介绍如何在Java中处理一对一(广播)和一对多(组播)的通信。本文概述的广播和组播概念是基于UDP协议的。

We start with a quick recap of datagrams and broadcasting and how it is implemented in Java. We also look into disadvantages of broadcasting and propose multicasting as an alternative to broadcasting.

我们首先快速回顾一下数据报和广播,以及它是如何在Java中实现的。我们还研究了广播的缺点,并建议用多播来替代广播。

Finally, we conclude by discussing support for these two addressing methods in both IPv4 and IPv6.

最后,我们将讨论在IPv4和IPv6中对这两种寻址方法的支持,作为结论。

2. Datagram Recap

2.数据图表回顾

As per the official definition of a datagram, “A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed”.

根据数据报的官方定义,”数据报是通过网络发送的独立的、自成一体的消息,其到达、到达时间和内容不受保证。”

In Java, the java.net package exposes the DatagramPacket and DatagramSocket classes that can be used for communication via the UDP protocol. UDP is typically used in scenarios where lower latency is more important than guaranteed delivery, such as audio/video streaming, network discovery, etc.

在Java中,java.net包公开了DatagramPacketDatagramSocket类,可用于通过UDP协议进行通信。UDP通常用于低延迟比保证交付更重要的场景,如音频/视频流、网络发现等。

To learn more about UDP and datagrams in Java, refer to A Guide to UDP in Java.

要了解有关Java中的UDP和数据报的更多信息,请参考A Guide to UDP in Java

3. Broadcasting

3 广播

Broadcasting is a one-to-all type of communication, i.e. the intention is to send the datagram to all the nodes in the network. Unlike in the case of point-to-point communication, we don’t have to know the target host’s IP Address. Instead, a broadcast address is used.

广播是一种一对一的通信类型,也就是说,其目的是将数据报发送到网络中的所有节点。与点对点通信的情况不同,我们不必知道目标主机的IP地址。相反,我们使用的是广播地址。

As per IPv4 Protocol, a broadcast address is a logical address, on which devices connected to the network are enabled to receive packets. In our example, we use a particular IP address, 255.255.255.255, which is the broadcast address of the local network.

根据IPv4协议,广播地址是一个逻辑地址,连接到网络的设备可以在这个地址上接收数据包。在我们的例子中,我们使用一个特定的IP地址,255.255.255,这是本地网络的广播地址。

By definition, routers connecting a local network to other networks don’t forward packets sent to this default broadcast address. Later we also show how we can iterate through all NetworkInterfaces, and send packets to their respective broadcast addresses.

根据定义,连接本地网络和其他网络的路由器不会转发发送到这个默认广播地址的数据包。稍后我们还将展示我们如何遍历所有的NetworkInterfaces,并将数据包发送到它们各自的广播地址。

First, we demonstrate how to broadcast a message. To this extent, we need to call the setBroadcast() method on the socket to let it know that the packet is to be broadcasted:

首先,我们演示如何广播一个消息。为此,我们需要在套接字上调用setBroadcast()方法,让它知道数据包要被广播。

public class BroadcastingClient {
    private static DatagramSocket socket = null;

    public static void main((String[] args)) throws IOException {
        broadcast("Hello", InetAddress.getByName("255.255.255.255"));
    }

    public static void broadcast(
      String broadcastMessage, InetAddress address) throws IOException {
        socket = new DatagramSocket();
        socket.setBroadcast(true);

        byte[] buffer = broadcastMessage.getBytes();

        DatagramPacket packet 
          = new DatagramPacket(buffer, buffer.length, address, 4445);
        socket.send(packet);
        socket.close();
    }
}

The next snippet shows how to iterate through all NetworkInterfaces to find their broadcast address:

下一个片段显示了如何遍历所有NetworkInterfaces以找到其广播地址。

List<InetAddress> listAllBroadcastAddresses() throws SocketException {
    List<InetAddress> broadcastList = new ArrayList<>();
    Enumeration<NetworkInterface> interfaces 
      = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface networkInterface = interfaces.nextElement();

        if (networkInterface.isLoopback() || !networkInterface.isUp()) {
            continue;
        }

        networkInterface.getInterfaceAddresses().stream() 
          .map(a -> a.getBroadcast())
          .filter(Objects::nonNull)
          .forEach(broadcastList::add);
    }
    return broadcastList;
}

Once we have the list of broadcast addresses, we can execute the code in the broadcast() method shown above for each of these addresses.

一旦我们有了广播地址的列表,我们就可以对这些地址中的每一个执行上面所示的broadcast()方法的代码。

There is no special code required on the receiving side to receive a broadcasted message. We can reuse the same code that receives a normal UDP datagram. A Guide to UDP in Java contains more details on this topic.

接收方不需要特别的代码来接收广播的信息。我们可以重新使用接收普通UDP数据报的相同代码。《Java中的UDP指南》包含了有关这一主题的更多细节。

4. Multicasting

4.组播[/strong

Broadcasting is inefficient as packets are sent to all nodes in the network, irrespective of whether they are interested in receiving the communication or not. This may be a waste of resources.

广播是低效的,因为数据包被发送到网络中的所有节点,而不管它们是否有兴趣接收该通信。这可能是一种资源的浪费。

Multicasting solves this problem and sends packets to only those consumers who are interested. Multicasting is based on a group membership concept, where a multicast address represents each group.

多播解决了这个问题,只向那些感兴趣的消费者发送数据包。多播是基于组成员的概念,其中一个多播地址代表每个组。

In IPv4, any address between 224.0.0.0 to 239.255.255.255 can be used as a multicast address. Only those nodes that subscribe to a group receive packets communicated to the group.

在IPv4中,224.0.0.0到239.255.255.255之间的任何地址都可以作为组播地址。只有那些订阅了一个组的节点才会收到传达给该组的数据包。

In Java, MulticastSocket is used to receive packets sent to a multicast IP. The following example demonstrates the usage of MulticastSocket:

在Java中,MulticastSocket被用来接收发送到组播IP的数据包。下面的例子演示了MulticastSocket的用法。

public class MulticastReceiver extends Thread {
    protected MulticastSocket socket = null;
    protected byte[] buf = new byte[256];

    public void run() {
        socket = new MulticastSocket(4446);
        InetAddress group = InetAddress.getByName("230.0.0.0");
        socket.joinGroup(group);
        while (true) {
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            socket.receive(packet);
            String received = new String(
              packet.getData(), 0, packet.getLength());
            if ("end".equals(received)) {
                break;
            }
        }
        socket.leaveGroup(group);
        socket.close();
    }
}

After binding the MulticastSocket to a port, we call the joinGroup() method, with the multicast IP as an argument. This is necessary to be able to receive the packets published to this group. The leaveGroup() method can be used to leave the group.

在将MulticastSocket绑定到一个端口后,我们调用joinGroup()方法,将多播IP作为参数。这是必要的,以便能够接收发布到该组的数据包。leaveGroup()方法可用于离开该组。

The following example shows how to publish to a multicast IP:

下面的例子显示了如何发布到一个多播IP。

public class MulticastPublisher {
    private DatagramSocket socket;
    private InetAddress group;
    private byte[] buf;

    public void multicast(
      String multicastMessage) throws IOException {
        socket = new DatagramSocket();
        group = InetAddress.getByName("230.0.0.0");
        buf = multicastMessage.getBytes();

        DatagramPacket packet 
          = new DatagramPacket(buf, buf.length, group, 4446);
        socket.send(packet);
        socket.close();
    }
}

5. Broadcast and IPv6

5.广播和IPv6

IPv4 supports three types of addressing: unicast, broadcast, and multicast. Broadcast, in theory, is a one-to-all communication, i.e. a packet sent from a device has the potential of reaching the entire internet.

IPv4支持三种类型的寻址:单播、广播和多播。广播,从理论上讲,是一种一对一的通信,即从一个设备发出的数据包有可能到达整个互联网。

As this is undesired for obvious reasons, the scope of the IPv4 broadcast was significantly reduced. Multicast, which also serves as a better alternative to broadcast, came in much later and hence lagged in adoption.

由于这是不可取的,原因显而易见,IPv4广播的范围被大大缩小。多播也是广播的一个更好的替代品,但它的出现要晚得多,因此在采用上也比较滞后。

In IPv6, multicast support has been made mandatory, and there is no explicit concept of broadcasting. Multicast has been extended and improved so that all broadcasting features can now be implemented with some form of multicasting.

在IPv6中,组播支持是强制性的,没有明确的广播概念。组播已被扩展和改进,因此所有广播功能现在都可以通过某种形式的组播来实现。

In IPv6, the left-most bits of an address are used to determine its type. For a multicast address, the first 8 bits are all ones, i.e. FF00::/8. Further, bit 113-116 represent the scope of the address, which can be either one of the following 4: Global, Site-local, Link-local, Node-local.

在IPv6中,地址的最左边的位被用来确定其类型。对于一个组播地址,前8位都是1,即FF00::/8。此外,第113-116位代表地址的范围,它可以是以下4种类型中的一种:全球、站点-本地、链接-本地、节点-本地。

In addition to unicast and multicast, IPv6 also supports anycast, in which a packet can be sent to any member of the group, but need not be sent to all members.

除了单播和组播之外,IPv6还支持任意广播,即一个数据包可以发送到组的任何成员,但不需要发送到所有成员。

6. Summary

6.总结

In this article, we explored the concepts of one-to-all and one-to-many type of communication using the UDP protocol. We saw examples of how to implement these concepts in Java.

在这篇文章中,我们探讨了使用UDP协议的一对一和一对多类型通信的概念。我们看到了如何在Java中实现这些概念的例子。

Finally, we also explored IPv4 and IPv6 support.

最后,我们还探讨了对IPv4和IPv6的支持。

Full example code is available over on Github.

完整的示例代码可在Github上获得