This is the 8th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

What is multicast

According to the number of receivers, network data transmission can be divided into the following three ways.

  • Unicast: Provides point-to-point communication. Each data sent by the sender has a unique destination address and is received by only one receiver. Both TCP sockets and UDP sockets described earlier support unicast only.
  • Broadcast: Data sent by the sender each time can be received by all receivers in the propagation range. The most typical is that television stations broadcast. The signal from the television station is sent to every point in its range. The signal reaches every TV set, whether it’s turned on or not. The IP protocol supports broadcasting, but the use of broadcasting is strictly limited because it will greatly increase the data traffic of the network. Routers can restrict broadcasting to local networks or subnets and prohibit broadcasting to the entire Internet. In addition, broadcasting of high bandwidth data, such as audio and video data, should be prohibited. Imagine if a live video stream was broadcast to hundreds of millions of Internet users, it would seriously overload the Internet and even crash.
  • Multicast: Data sent by the sender each time can be received by all receivers in the group. The reception range of multicast is between unicast and broadcast. The hosts that are interested in a particular topic join the same multicast group, and the data sent to this group will reach all the hosts in the group but not the hosts outside the group.

When the sender wants to send the same data to 1000 receivers, if unicast is adopted, 1000 copies of the data will be copied at the sender and sent to each receiver respectively. This transmission mode is inefficient, because it unnecessarily copies the data and wastes a lot of network bandwidth. If multicast is used, transmission efficiency can be greatly improved. Routers dynamically route multicast data and copy data only when necessary.

For example, in the following example, host 1 multicast data to hosts 2, 3, 4, and 5. Data is replicated only on routers 2 and 3. Data does not need to be replicated on other nodes. On the path from host 1 to router 2, data is transmitted only once. If unicast is used, the data is copied four times on host 1 before being sent. In the transmission path from host 1 to router 2, the data needs to be repeated four times.

Multicast All hosts in a multicast group share the same address. This address is called a multicast address. The multicast address is a P address that ranges from 224.0.0.0 to 239.255.255.255. The first four bits of all addresses in this range. Is “1110”. Multicast addresses are also known as Class D IP addresses, distinguished from other class A, B, and C addresses. A multicast group is open and a host can enter or leave the group at any time.

Most of the multicast data is audio or video, which is usually large enough that if part of the data is lost in transit, the receiver can still recognize the signal. Thus, multicast data is sent over UDP, which is unreliable but more than three times faster than connection-oriented TCP.

Multicast differs from unicast UDP in that it must take into account the TTL (Time To Live) value. TTL determines the TTL of an IP packet by limiting the number of routers that an IP packet can pass through before being discarded. Each time an IP packet passes through a router, the TTL decreases by 1. When the TTL becomes 0, the packet is discarded. One purpose of TTL is to prevent misconfigured routers from passing packets back and forth between routers indefinitely, and another is to limit the geographic range of multicast. For example, when the TTL is 16, packets are restricted to propagation within the local zone, and when the TTL is 255, packets are sent to the entire world. However, TTL does not precisely determine the geographical extent of packet propagation. In general, the farther away the receiver is, the more routers the packet has to pass through. A packet with a small TTL will not travel farther than a packet with a large TTL. It is worth noting that, regardless of the TTL value, if a packet is sent to a multicast group with addresses between 224.0.0.0 and 224.0.0.255, the packet will only be propagated within the local subnet and will not be forwarded to other networks.

To send and receive multicast data outside the local subnet, a multicast router (MROUTER) must be configured on the local network. You can check whether mrOUTER is configured from the network administrator or run the “ping all-Routers.mcast.net” command. If a router responds, then mrOUTER is on the network.

Moreover, even if MrOUTER is configured on the subnet, multicast data from every host on the Internet cannot be guaranteed to be sent and received. For a packet to reach any address in a multicast group, a transport path consisting of multiple MrOuter is required between the sending and receiving hosts. If such a path does not exist, the packet cannot reach each receiving host.

MulticastSocket class

An overview

Java.net.MulticastSocket has multicast functionality. It is a subclass of DatagramSocket. Like DatagramSocket, MulticastSocket is used with DatagramPacket. DatagramPacket is used to store received and sent multicast datagrams. If you want to receive multicast datagrams, you simply create a MulticastSocket, add it to the multicast group, and receive multicast datagrams sent to that group.

Sending multicast datagrams is very similar to sending unicast datagrams in that you simply create a MulticastSocket and send data to a multicast group without adding it to a multicast group (which you can of course add). The difference between sending multicast datagrams and sending unicast datagrams is that setTimeToLive() can be called first to set the TTL of multicast datagrams.

Before you start learning about the MulticastSocket class, it’s a good idea to learn about UDP and MulticastSocket and DatagramPacket. See these two blogs: Java network programming (six) – UDP programming (a) – nuggets (juejin. Cn), Java network programming (seven) – UDP programming (two) – nuggets (juejin. Cn).

A constructor

MulticastSocket has the following three constructors

public MulticastSocket(a) throws SocketException
public MulticastSocket(int port) throws SocketException
public MulticastSocket(SocketAddress bindAddress) throws SocketException
Copy the code

The first no-argument constructor binds MulticastSocket to an anonymous port and can be used for programs that send only multicast data. The remaining two constructors bind MulticastSocket to a specific known port, and can be used by programs that receive multicast data so that multicast data sent by a sender can be easily addressed to that MulticastSocket.

For the third constructor, if the argument is set to null, MulticastSocket is not bound to any local ports, and the program then calls bind() again. For example, the following way

MulticastSocket ms = new MulticastSocket(null);
ms.setReuseAddress(false);// Set the MulticastSocket option to disallow the reuse of binding addresses
SocketAddress address = new InetSocketAddress(3000);
ms.bind(address);
Copy the code

Communicates with multicast groups

MulticastSocket communicates with multicast groups using the following four operations:

1. Join a multicast group: joinGroup() 2. Send a datagram to a multicast group member: send() 3. 4. Leave the multicast group: leaveGroup()Copy the code

The send() and receive() methods are directly inherited from the parent DatagramSocket, and the joinGroup() and leaveGroup() methods are MulticastSocket specific. Note that MulticastSocket must join the group to receive data sent to it, and must join the group to leave it. However, MulticastSocket does not have to join a group to send data to that group.

The joinGroup() method is used to join a multicast group. A MulticastSocket can call the joinGroup() method multiple times to join multiple multicast groups. In addition, multiple MulticastSockets on the same host, or multiple MulticastSockets within the same program on the host, can be added to the same multicast group, and each MulticastSocket receives data sent to that group. The joinGroup() method has two overloaded forms:

public void joinGroup(InetAddress address)throws IOException
public void joinGroup(SocketAddress address,NetworkInterface interface) throws IOException
Copy the code

In the first joinGroup() method, address specifies a multicast IP address that must be between 224.0.0.0 and 239.255.255.255, otherwise IOException will be thrown. In the second joinGroup() method, address specifies the multicast address and interface specifies the network interface. With this approach, you can qualify MulticastSocket to receive only multicast datagrams from a network interface.

The leaveGroup() method is used to leave a multicast group. After MulticastSocket leaves a group, it can no longer receive datagrams to that group. It has the following two overloaded forms:

public void leaveGroup(InetAddress address)throws IOException
public void leaveGroup(SocketAddress address,NetworkInterface interface) throws IOException
Copy the code

The address parameter specifies the multicast address to leave. If the attempted multicast address is not a multicast address, the leaveGroup() method throws an IOException. However, if MulticastSocket leaves an unjoined group, the leaveGroup() method does not throw any exceptions. The interface parameter specifies that multicast datagrams from a network interface are no longer wanted. It is possible for MulticastSocket to initially join the multicast group of all the network interfaces and then leave the group in one of the network interfaces through the second leaveGroup() method.

Sets and gets the MulticastSocket property

MuliticastSocket provides two sets of methods for setting up and reading network interfaces. MuliticastSocket sends and receives multicast data only to groups on the network interface:

1 Group 1 method public void setInterface(InetAddress Address)throws SocketException Public InetAddress getInterface()throws SocketException // Group 2 method public void setNetworkInterface(NetworkInterface interface)throws SocketException public NetworkInterface getNetworkInterface( throws SocketExceptionCopy the code

The above two groups of methods have the same effect. The difference is that the first group of methods uses the InetAddress class to represent the NetworkInterface, while the second group of methods uses the NetworkInterface class to represent the NetworkInterface. A NetworkInterface object represents a NetworkInterface that has a unique domain name and can contain one or more IP addresses.

The MuliticastSocket class provides methods for setting and reading TTL properties:

public void setTimeToLive(int ttl) throws IOException
public int getTimeToLive() throws IOException
Copy the code

MuliticastSocket sample

Use MuliticastSocket to continuously send data to a multicast group at IP address 224.0.0.1. The data is the current time. MuliticastSocket sends and receives data almost the same as DatagramSocket. However, as a sender, you can choose to join the group or not

MuliticastSocket receiver

public class MulticastReceiver {
    public static void main(String[] args) throws Exception {
        InetAddress group = InetAddress.getByName("224.0.0.1");
        int port = 5555;
        MulticastSocket ms = null;
        try {
            ms = new MulticastSocket(port);
            ms.joinGroup(group);// Add to the multicast group
            byte[] buffer = new byte[8192];
            while (true) {
                DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
                ms.receive(dp);// Receive multicast datagrams
                String s = new String(dp.getData(), 0, dp.getLength()); System.out.println(s); }}catch (IOException e){
            e.printStackTrace();
        }finally
        {
            if(ms ! =null)
            {
                try
                {
                    ms.leaveGroup(group);
                    ms.close();
                } catch (IOException e) { }
            }
        }
    }
}
Copy the code

MuliticastSocket sender

public class MulticastSender {

    public static void main(String[] args) throws IOException {
        InetAddress group = InetAddress.getByName("224.0.0.1");
        int port = 5555;
        MulticastSocket ms = null;

        try {
            ms = new MulticastSocket(port);
            ms.joinGroup(group);// Add to the multicast group
            while (true) {
                String message = "Hello " + new java.util.Date();
                byte[] buffer = message.getBytes();
                DatagramPacket dp = new DatagramPacket(buffer, buffer.length, group, port);
                ms.send(dp);// Send multicast datagrams
                System.out.println("Send datagrams to" + group + ":" + port);
                Thread.sleep(1000); }}catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(ms ! =null) {
                try {
                    ms.leaveGroup(group);
                    ms.close();
                } catch (IOException e) {
                }

            }
        }
    }
}
Copy the code