MulticastClient.java Source code

Java tutorial

Introduction

Here is the source code for MulticastClient.java

Source

    /* From http://java.sun.com/docs/books/tutorial/index.html */

    /*
     * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions are met:
     *
     * -Redistribution of source code must retain the above copyright notice, this
     *  list of conditions and the following disclaimer.
     *
     * -Redistribution in binary form must reproduce the above copyright notice,
     *  this list of conditions and the following disclaimer in the documentation
     *  and/or other materials provided with the distribution.
     *
     * Neither the name of Sun Microsystems, Inc. or the names of contributors may
     * be used to endorse or promote products derived from this software without
     * specific prior written permission.
     *
     * This software is provided "AS IS," without a warranty of any kind. ALL
     * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
     * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
     * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
     * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
     * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
     * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
     * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
     * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
     * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
     * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
     *
     * You acknowledge that this software is not designed, licensed or intended
     * for use in the design, construction, operation or maintenance of any
     * nuclear facility.
     */

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

public class MulticastClient {

   public static void main(String[] args) throws IOException {

      MulticastSocket socket = new MulticastSocket(4446);
      InetAddress address = InetAddress.getByName("230.0.0.1");
      socket.joinGroup(address);

      DatagramPacket packet;

      // get a few quotes
      for (int i = 0; i < 5; i++) {

         byte[] buf = new byte[256];
         packet = new DatagramPacket(buf, buf.length);
         socket.receive(packet);

         String received = new String(packet.getData());
         System.out.println("Quote of the Moment: " + received);
      }

      socket.leaveGroup(address);
      socket.close();
   }

}

    /////////////////////////////////////////////////

    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    import java.util.Date;

    public class MulticastServer {
        public static void main(String[] args) throws java.io.IOException {
            new MulticastServerThread().start();
        }
    }

    class MulticastServerThread extends QuoteServerThread {

        private long FIVE_SECONDS = 5000;

        public MulticastServerThread() throws IOException {
            super("MulticastServerThread");
        }

        public void run() {
            while (moreQuotes) {
                try {
                    byte[] buf = new byte[256];

                    // construct quote
                    String dString = null;
                    if (in == null)
                        dString = new Date().toString();
                    else
                        dString = getNextQuote();
                    buf = dString.getBytes();

                    // send it
                    InetAddress group = InetAddress.getByName("230.0.0.1");
                    DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446);
                    socket.send(packet);

                    // sleep for a while
                    try {
                        sleep((long) (Math.random() * FIVE_SECONDS));
                    } catch (InterruptedException e) {
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    moreQuotes = false;
                }
            }
            socket.close();
        }
    }

    class QuoteServerThread extends Thread {

        protected DatagramSocket socket = null;

        protected BufferedReader in = null;

        protected boolean moreQuotes = true;

        public QuoteServerThread() throws IOException {
            this("QuoteServerThread");
        }

        public QuoteServerThread(String name) throws IOException {
            super(name);
            socket = new DatagramSocket(4445);

            try {
                in = new BufferedReader(new FileReader("one-liners.txt"));
            } catch (FileNotFoundException e) {
                System.err.println("Could not open quote file. Serving time instead.");
            }
        }

        public void run() {

            while (moreQuotes) {
                try {
                    byte[] buf = new byte[256];

                    // receive request
                    DatagramPacket packet = new DatagramPacket(buf, buf.length);
                    socket.receive(packet);

                    // figure out response
                    String dString = null;
                    if (in == null)
                        dString = new Date().toString();
                    else
                        dString = getNextQuote();
                    buf = dString.getBytes();

                    // send the response to the client at "address" and "port"
                    InetAddress address = packet.getAddress();
                    int port = packet.getPort();
                    packet = new DatagramPacket(buf, buf.length, address, port);
                    socket.send(packet);
                } catch (IOException e) {
                    e.printStackTrace();
                    moreQuotes = false;
                }
            }
            socket.close();
        }

        protected String getNextQuote() {
            String returnValue = null;
            try {
                if ((returnValue = in.readLine()) == null) {
                    in.close();
                    moreQuotes = false;
                    returnValue = "No more quotes. Goodbye.";
                }
            } catch (IOException e) {
                returnValue = "IOException occurred in server.";
            }
            return returnValue;
        }
    }

    //file: one-liners.txt

    /*
    Life is wonderful. Without it we'd all be dead.
    Daddy, why doesn't this magnet pick up this floppy disk?
    Give me ambiguity or give me something else.
    I.R.S.: We've got what it takes to take what you've got!
    We are born naked, wet and hungry. Then things get worse.
    Make it idiot proof and someone will make a better idiot.
    He who laughs last thinks slowest!
    Always remember you're unique, just like everyone else.
    "More hay, Trigger?" "No thanks, Roy, I'm stuffed!"
    A flashlight is a case for holding dead batteries.
    Lottery: A tax on people who are bad at math.
    Error, no keyboard - press F1 to continue.
    There's too much blood in my caffeine system.
    Artificial Intelligence usually beats real stupidity.
    Hard work has a future payoff. Laziness pays off now.
    "Very funny, Scotty. Now beam down my clothes."
    Puritanism: The haunting fear that someone, somewhere may be happy.
    Consciousness: that annoying time between naps.
    Don't take life too seriously, you won't get out alive.
    I don't suffer from insanity. I enjoy every minute of it.
    Better to understand a little than to misunderstand a lot.
    The gene pool could use a little chlorine.
    When there's a will, I want to be in it.
    Okay, who put a "stop payment" on my reality check?
    We have enough youth, how about a fountain of SMART?
    Programming is an art form that fights back.
    "Daddy, what does FORMATTING DRIVE C mean?"
    All wiyht. Rho sritched mg kegtops awound?
    My mail reader can beat up your mail reader.
    Never forget: 2 + 2 = 5 for extremely large values of 2.
    Nobody has ever, ever, EVER learned all of WordPerfect.
    To define recursion, we must first define recursion.
    Good programming is 99% sweat and 1% coffee.
    Home is where you hang your @
    The E-mail of the species is more deadly than the mail.
    A journey of a thousand sites begins with a single click.
    You can't teach a new mouse old clicks.
    Great groups from little icons grow.
    Speak softly and carry a cellular phone.
    C:\ is the root of all directories.
    Don't put all your hypes in one home page.
    Pentium wise; pen and paper foolish.
    The modem is the message.
    Too many clicks spoil the browse.
    The geek shall inherit the earth.
    A chat has nine lives.
    Don't byte off more than you can view.
    Fax is stranger than fiction.
    What boots up must come down.
    Windows will never cease.   (ed. oh sure...)
    In Gates we trust.    (ed.  yeah right....)
    Virtual reality is its own reward.
    Modulation in all things.
    A user and his leisure time are soon parted.
    There's no place like http://www.home.com
    Know what to expect before you connect.
    Oh, what a tangled website we weave when first we practice.
    Speed thrills.
    Give a man a fish and you feed him for a day; teach him to use the Net and he won't bother you for weeks.
    
    
    */