官术网_书友最值得收藏!

UDP and multicasting

Multicasting is a useful technique to use if you need to send messages to a group on a periodic basis. It uses a UDP server and one or more UDP clients. To illustrate this capability, we will create a simple time server. The server will send a date and time string to clients every second.

Multicasting will send an identical message to every member of a group. A group is identified by a multicast address. A multicast address must use the following IP address range: 224.0.0.0 through 239.255.255.255. The server will send a message mark with this address. Clients must join the group before they can receive any multicast messages.

Creating a multicast server

A MulticastServer class is declared next, where a DatagramSocket instance is created. The try-catch blocks will handle exceptions as they occur:

public class MulticastServer {
    public static void main(String args[]) {
        System.out.println("Multicast  Time Server");
        DatagramSocket serverSocket = null;
        try {
            serverSocket = new DatagramSocket();
            ...
            }
        } catch (SocketException ex) {
            // Handle exception
        } catch (IOException ex) {
            // Handle exception
        }
    }
}

The body of the try block uses an infinite loop to create an array of bytes to hold the current date and time. Next, an InetAddress instance representing the multicast group is created. Using the array and the group address, a DatagramPacket is instantiated and used as an argument to the DatagramSocket class' send method. The data and time sent is then displayed. The server then pauses for one second:

    while (true) {
        String dateText = new Date().toString();
        byte[] buffer = new byte[256];
        buffer = dateText.getBytes();

        InetAddress group = InetAddress.getByName("224.0.0.0");
        DatagramPacket packet;
        packet = new DatagramPacket(buffer, buffer.length, 
            group, 8888);
        serverSocket.send(packet);
        System.out.println("Time sent: " + dateText);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            // Handle exception
        }
    }

This server only broadcasts messages. It never receives messages from a client.

Creating the multicast client

The client is created using the following MulticastClient class. In order to receive a message, the client must use the same group address and port number. Before it can receive messages, it must join the group using the joinGroup method. In this implementation, it receives 5 date and time messages, displays them, and then terminates. The trim method removes leading and trailing white space, from a string. Otherwise, all 256 bytes of the message will be displayed:

public class MulticastClient {
    public static void main(String args[]) {
        System.out.println("Multicast  Time Client");
        try (MulticastSocket socket = new MulticastSocket(8888)) {
            InetAddress group = 
                InetAddress.getByName("224.0.0.0");
            socket.joinGroup(group);
            System.out.println("Multicast  Group Joined");

            byte[] buffer = new byte[256];
            DatagramPacket packet = 
                new DatagramPacket(buffer, buffer.length);

            for (int i = 0; i < 5; i++) {
                socket.receive(packet);
                String received = new String(packet.getData());
                System.out.println(received.trim());
            }
            
            socket.leaveGroup(group);
        } catch (IOException ex) {
            // Handle exception
        }
        System.out.println("Multicast  Time Client Terminated");
    }
}

When the server is started, the messages sent are displayed as shown here:

Multicast Time Server

Time sent: Thu Jul 09 13:19:49 CDT 2015

Time sent: Thu Jul 09 13:19:50 CDT 2015

Time sent: Thu Jul 09 13:19:51 CDT 2015

Time sent: Thu Jul 09 13:19:52 CDT 2015

Time sent: Thu Jul 09 13:19:53 CDT 2015

Time sent: Thu Jul 09 13:19:54 CDT 2015

Time sent: Thu Jul 09 13:19:55 CDT 2015

...

The client output will look similar to the following:

Multicast Time Client

Multicast Group Joined

Thu Jul 09 13:19:50 CDT 2015

Thu Jul 09 13:19:51 CDT 2015

Thu Jul 09 13:19:52 CDT 2015

Thu Jul 09 13:19:53 CDT 2015

Thu Jul 09 13:19:54 CDT 2015

Multicast Time Client Terminated

Note

If the example is executed on a Mac, you may receive an exception indicating that it cannot assign the requested address. This can be fixed by using the JVM option -Djava.net.preferIPv4Stack=true.

There are numerous other multicast capabilities, which will be explored in Chapter 6, UDP and Multicasting.

主站蜘蛛池模板: 监利县| 巴里| 乌拉特前旗| 上犹县| 青铜峡市| 安新县| 沁水县| 湘西| 高清| 兴仁县| 新化县| 海南省| 昌邑市| 汉沽区| 罗甸县| 凭祥市| 绍兴市| 巧家县| 通渭县| 雷波县| 松潘县| 弥渡县| 于都县| 北宁市| 固原市| 同江市| 莫力| 安国市| 花莲市| 瑞昌市| 太康县| 青河县| 沙雅县| 柏乡县| 富民县| 临西县| 太保市| 石景山区| 社会| 甘肃省| 建平县|