MulticastSender.java Source code

Java tutorial

Introduction

Here is the source code for MulticastSender.java

Source

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MulticastSender {

    public static void main(String[] args) {

        InetAddress ia = null;
        int port = 0;
        String characters = "Here's some multicast data\n";
        byte[] data = new byte[characters.length()];

        // read the address from the command line
        try {
            try {
                ia = InetAddress.getByName(args[0]);
            } catch (UnknownHostException e) {
                //ia = InetAddressFactory.newInetAddress(args[0]);
            }
            port = Integer.parseInt(args[1]);
        } catch (Exception e) {
            System.err.println(e);
            System.err.println("Usage: java MulticastSender MulticastAddress port");
            System.exit(1);
        }

        characters.getBytes(0, characters.length(), data, 0);
        DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);

        try {
            MulticastSocket ms = new MulticastSocket();
            ms.joinGroup(ia);
            for (int i = 1; i < 10; i++) {
                ms.send(dp, (byte) 1);
            }
            ms.leaveGroup(ia);
            ms.close();
        } catch (SocketException se) {
            System.err.println(se);
        } catch (IOException ie) {
            System.err.println(ie);
        }

    }

}