[network programming] java udp multicast program uses multicast socket to send and receive data

Posted by uwannadonkey on Sat, 22 Jan 2022 23:06:24 +0100

Introduction to network communication

According to the number of recipients, network data transmission can be divided into the following three ways.
·Unicast: provides point-to-point communication. The data sent by the sender each time has a unique destination address and is received by only one receiver.
·Broadcast: the data sent by the sender each time can be received by all receivers within the propagation range. Television stations use broadcasting. The signal transmitted from the television station is sent to each point within the propagation range. Whether the TV is turned on or not, the signal can reach each TV. IP supports broadcasting, but broadcasting will greatly increase the network data traffic, so the use of broadcasting is strictly limited. The router can restrict broadcasting to the local network or subnet and prohibit broadcasting to the whole Internet. In addition, the broadcasting of high bandwidth data, such as audio and video data, should be prohibited. Imagine that if a real-time video stream is broadcast to hundreds of millions of Internet users, the Internet will be seriously overloaded and even collapse.
·Multicast: the data sent by the sender each time can be received by all receivers in the group. The receiving range of multicast is between unicast and broadcast. Hosts interested in specific topics join the same multicast group. The data sent to this group will reach all hosts in the group, but will not reach hosts outside the group. When the sender wants to send the same data to 1000 receivers, if unicast is adopted, the data will be copied 1000 copies at the sender and transmitted to each receiver respectively. This transmission method is very inefficient because it makes unnecessary copies of the data and wastes a lot of network bandwidth. If multicast is adopted, the transmission efficiency can be greatly improved. The router will dynamically determine the route of multicast data and copy the data only when necessary

Multicast

All hosts in a multicast group share the same address, which is called a multicast address. The multicast address is an IP address ranging from 224.0.0.0 to 239.255.255.255. The first four binary bits of all addresses in this range are "1110". Multicast address is also called class D IP address, which is different from other class A, class B and class C addresses. The multicast group is open, and the host can enter or leave the group at any time. IPv6 multicast addresses start with the hexadecimal value 0xFF (the corresponding binary value is 11111111)
IANA (Internet Assigned Numbers Authority) organization is responsible for distributing permanent multicast addresses. So far, it has assigned hundreds of addresses. Most assigned addresses begin with 224.0, 224.1, 224.2, or 239,

8-1 permanent multicast address

Table 8-1 lists some permanent multicast addresses. The complete multicast address assignment list can be obtained from iana's official website. The remaining 248 million class D addresses can be used for temporary purposes by anyone who needs them. Multicast router (mrouter) is responsible for ensuring that two different network systems do not use the same class D address at the same time. As can be seen from table 8-1, like other IP addresses, multicast addresses can also have domain names. For example, the domain name of multicast address 224.0.1.1 is NTP mcast. net.
Most multicast data are audio or video. These data are generally large. Even if some data is lost during transmission, the receiver can still recognize the signal. Therefore, multicast data sent through UDP is unreliable, but it is more than three times faster than connection oriented TCP. The difference between multicast and unicast UDP is that the former must consider the TTL (Time To Live) value, which is represented by 1 byte of the header of the IP packet. TTL determines the lifetime of IP packets by limiting the number of routers that IP packets pass through before being discarded. Every time an IP packet passes through a router, the TTL is reduced by 1. When the TTL becomes 0, the packet is discarded. One function of TTL is to prevent incorrectly configured routers from transmitting packets back and forth between routers indefinitely, and another function is to limit the geographical scope of multicast. For example, when the TTL is 16, the packet is limited to the local region. When the TTL is 255, the packet will be sent to the whole world. However, TTL cannot accurately determine the geographical range of packet propagation. Generally, the farther the receiver is away, the more routers the packet will pass through. Packets with small TTL value will not propagate farther than packets with large TTL value. Table 8-2 lists the rough correspondence between TTL values and the geographical range of packet propagation. It is worth noting that no matter what the TTL value is, if the packet is sent to a multicast group with addresses between 224.0.0.0 and 224.0.0.255, the packet will only propagate in the local subnet and will not be forwarded to other networks.

If you want to send and receive multicast data outside the local subnet, you need to configure a multicast router (mrouter) on the local network. You can learn whether mrouter is configured from the network administrator, or run the command "Ping all routes. Mcast. Net". If there is a router response, it indicates that there is mrouter on the network. In addition, even if mrouter is configured on the subnet, it can not guarantee to send and receive multicast data from each host on the Internet. If the packet can reach any address in the multicast group, it needs to exist between the sending host and the receiving host
.

Code - send datagram

Conditions the network debugging wizard software of a LAN mobile phone is very convenient. You can view the received datagram on it:
192.168.1.100 is the automatic port on the mobile phone (I don't understand why it is different from the ip of ipconfig on the computer. It is clearly a LAN)


    public static void main(String[] args) throws IOException, InterruptedException {
        Net net = new Net();
        MulticastSocket multicastSocket2 =new MulticastSocket(null);
        SocketAddress socketAddress = new InetSocketAddress(4000);
        InetAddress group =InetAddress.getByName("192.168.1.100");
        int port = 4000;
        multicastSocket2.bind(socketAddress);
        String msg = "hello"+new java.util.Date();

        byte[]buffer = msg.getBytes(StandardCharsets.UTF_8);
  DatagramPacket packet = new DatagramPacket(buffer,buffer.length,group,port);
  while(true) {
      Thread.sleep(5000);
      multicastSocket2.send(packet);
  }
    }
}

summary

Multicast is a form of multi-point delivery. It uses hardware technology to communicate by using a large number of multicast addresses. When a group of machines need to communicate, select a multicast address, configure the corresponding network interface hardware, identify the multicast address, and receive a copy of the packet on the multicast address.

There are not many applications of network technology. Online video conference and online video viewing are particularly suitable for multicast.
broadcasting is the most common form of multicast. It delivers a copy of a packet to each destination. It can be completed by the delivery of multiple single packets, or the copy of the packet can be transmitted through a separate connection until each receiver receives a copy.

A large number of broadcast packets cannot appear in the network for a long time, otherwise there will be the so-called "broadcast storm". Broadcast storm is that the network is occupied by a large number of broadcast packets for a long time, and the normal point-to-point communication cannot be carried out normally. The external performance is that the network speed is extremely slow. There are many reasons for broadcast storm. A faulty network card may send broadcast packets to the network for a long time, resulting in broadcast storm.

Broadcast storms cannot be completely eliminated, but they can only spread in the same subnet, just as the sound of speakers can only spread in the same venue. Therefore, in large and medium-sized LAN composed of hundreds or even thousands of computers, subnet division is generally carried out, just like isolating a large hall into many small halls with walls, so as to achieve the purpose of isolating broadcast storms.

In the IP network, the broadcast address is represented by the IP address "255.255". This IP address represents all IP addresses in the same subnet.

Multicast in IP network is generally realized by multicast IP address. Multicast IP address refers to class D IP address, i.e. IP address between 224.0.0.0 and 239.255.255.255. DHCP manager in Windows 2000 supports automatic allocation of multicast IP addresses
TCP is a reliable connection oriented transport protocol, while UDP is a connectionless and unreliable transport protocol. Datagram socket and datagram channel are based on UDP. When sending datagrams through them, if the datagram fails to reach the destination, the sender will not be notified and the program will not throw an exception; When receiving datagrams through them, if the capacity of the buffer used to store datagrams is less than the size of the received datagrams, the excess data will be discarded, the receiver will not be notified, and the program will not throw an exception. Although DatagramSocket and DatagramChannel also have the connect() method, this method has different functions from the connect() method of TCP Socket. The former does not establish a connection in the sense of TCP, but restricts the current datagram socket or datagram channel to send and receive datagrams only to the remote host and UDP port specified by the parameter. Datagram socket is used in conjunction with datagram packet, which is used to store received or sent data. DatagramChannel is used in combination with ByteBuffer, which is used to store received or sent data. Datagram socket can only work in blocking mode, while datagram channel supports blocking and non blocking modes.
MulticastSocket is a subclass of datagram socket. It can send and receive multicast datagrams * *. MulticastSocket must join a multicast group to receive datagrams sent to the group * *. All multicastsockets in a multicast group share the same multicast IP address. The multicast IP address ranges from 224.0.0.0 to 239.255.255.255.

Code 2 uses datagrams to receive data sent by other users

effect:


Note that the ip and port should be the same

public class Test implements Runnable{
    private static final String BROADCAST_IP = "230.0.0.1";
    // Use a constant as the port for multicast purposes of this program
    public static final int BROADCAST_PORT = 30000;
    // Define the maximum size of each datagram as 4K
    private static final int DATA_LEN = 4096;
    // Define the MulticastSocket instance of this program
    private MulticastSocket socket = null;
    private InetAddress broadcastAddress = null;
    private Scanner scan = null;
    // Defines the byte array for receiving network data
    byte[] inBuff = new byte[DATA_LEN];
    // Creates a DatagramPacket object that is ready to accept data with the specified byte array
    private DatagramPacket inPacket = new DatagramPacket(inBuff, inBuff.length);
    // Define a datagram packet object for sending
    private DatagramPacket outPacket = null;
    public void init() throws IOException {
        try {
// Create a MulticastSocket object for sending and receiving data
// Because the MulticastSocket object needs to receive, it has a specified port
            socket = new MulticastSocket(BROADCAST_PORT);
            broadcastAddress = InetAddress.getByName(BROADCAST_IP);
// Add the socket to the specified multicast address
            socket.joinGroup(broadcastAddress);
// Set the datagram sent by this MulticastSocket to be sent back to itself
            socket.setLoopbackMode(false);
// Initialize the datagram socket for sending, which contains a byte array with length of 0
            outPacket = new DatagramPacket(new byte[0], 0, broadcastAddress, BROADCAST_PORT);
// Start the thread with the run() method of this instance as the thread body
            new Thread(this).start();
// Create keyboard input stream
            scan = new Scanner(System.in);
// Constantly read keyboard input
            while (scan.hasNextLine()) {
// Converts a line of string entered by the keyboard into a byte array
                byte[] buff = scan.nextLine().getBytes();
// Set byte data in datagram packet for transmission
                outPacket.setData(buff);
// Send datagram
                socket.send(outPacket);
            }
        } finally {
            socket.close();
        }
    }
    public void run() {
        try {
            while (true) {
// Read the data in the Socket and put the read data in the byte array encapsulated by inPacket.
                socket.receive(inPacket);
// Print out the contents read from the socket
                System.out.println("Chat message:" + new String(inBuff, 0, inPacket.getLength()));
            }
        }
// Catch exception
        catch (IOException ex) {
            ex.printStackTrace();
            try {
                if (socket != null) {
// Let the Socket leave the multicast IP address
                    socket.leaveGroup(broadcastAddress);
// Close the Socket object
                    socket.close();
                }
                System.exit(1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws IOException {
        new Test().init();
    }
}

Topics: Java network socket