QuoteServerThread.java Source code

Java tutorial

Introduction

Here is the source code for QuoteServerThread.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.
     */

    /*
     * 1.1 version.
     */

    import java.io.*;
    import java.net.*;
    import java.util.*;

class QuoteServerThread extends Thread {
    private DatagramSocket socket = null;
    private BufferedReader qfs = null;
    private boolean moreQuotes = true;

    QuoteServerThread() {
        super("QuoteServer");
        try {
            socket = new DatagramSocket();
            System.out.println("QuoteServer listening on port: " + socket.getLocalPort());
        } catch (java.io.IOException e) {
            System.err.println("Could not create datagram socket.");
        }
        this.openInputFile();
    }

    public void run() {
        if (socket == null)
            return;

        while (moreQuotes) {
            try {
                byte[] buf = new byte[256];
                DatagramPacket packet;
                InetAddress address;
                int port;
                String dString = null;

                    // receive request
                packet = new DatagramPacket(buf, 256);
                socket.receive(packet);
                address = packet.getAddress();
                port = packet.getPort();

                    // send response
                if (qfs == null)
                    dString = new Date().toString();
                else
                    dString = getNextQuote();
                buf = dString.getBytes();
                packet = new DatagramPacket(buf, buf.length, address, port);
                socket.send(packet);
            } catch (IOException e) {
                System.err.println("IOException:  " + e);
                moreQuotes = false;
                e.printStackTrace();
            }
        }
   socket.close();
    }

    private void openInputFile() {
        try {
            qfs = new BufferedReader(new InputStreamReader(new FileInputStream("one-liners.txt")));
        } catch (java.io.FileNotFoundException e) {
            System.err.println("Could not open quote file. Serving time instead.");
        }
    }
    private String getNextQuote() {
        String returnValue = null;
        try {
            if ((returnValue = qfs.readLine()) == null) {
                qfs.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.
    
    
    */

    /*
     * This is the same in 1.0 as in 1.1.
     */

    class QuoteServer {
        public static void main(String[] args) {
            new QuoteServerThread().start();
        }
    }

    /*
     * 1.1 version.
     */

    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;

    public class QuoteClientApplet extends Applet implements ActionListener {
        boolean DEBUG = false;
        InetAddress address;
        TextField portField;
        Label display;
        DatagramSocket socket;

        public void init() {
            //Initialize networking stuff.
            String host = getCodeBase().getHost();

            try {
                address = InetAddress.getByName(host);
            } catch (UnknownHostException e) {
                System.out.println("Couldn't get Internet address: Unknown host");
                // What should we do?
            }

            try {
                socket = new DatagramSocket();
            } catch (IOException e) {
                System.out.println("Couldn't create new DatagramSocket");
                return;
            }

            //Set up the UI.
            GridBagLayout gridBag = new GridBagLayout();
            GridBagConstraints c = new GridBagConstraints();
            setLayout(gridBag);

            Label l1 = new Label("Quote of the Moment:", Label.CENTER);
            c.anchor = GridBagConstraints.SOUTH;
            c.gridwidth = GridBagConstraints.REMAINDER;
            gridBag.setConstraints(l1, c);
            add(l1);

            display = new Label("(no quote received yet)", Label.CENTER);
            c.anchor = GridBagConstraints.NORTH;
            c.weightx = 1.0;
            c.fill = GridBagConstraints.HORIZONTAL;
            gridBag.setConstraints(display, c);
            add(display);

            Label l2 = new Label("Enter the port (on host " + host + ") to send the request to:", Label.RIGHT);
            c.anchor = GridBagConstraints.SOUTH;
            c.gridwidth = 1;
            c.weightx = 0.0;
            c.weighty = 1.0;
            c.fill = GridBagConstraints.NONE;
            gridBag.setConstraints(l2, c);
            add(l2);

            portField = new TextField(6);
            gridBag.setConstraints(portField, c);
            add(portField);

            Button button = new Button("Send");
            gridBag.setConstraints(button, c);
            add(button);

            portField.addActionListener(this);
            button.addActionListener(this);
        }

        public Insets getInsets() {
            return new Insets(4, 4, 5, 5);
        }

        public void paint(Graphics g) {
            Dimension d = getSize();
            Color bg = getBackground();

            g.setColor(bg);
            g.draw3DRect(0, 0, d.width - 1, d.height - 1, true);
            g.draw3DRect(3, 3, d.width - 7, d.height - 7, false);
        }

        void doIt(int port) {
            DatagramPacket packet;
            byte[] sendBuf = new byte[256];

            packet = new DatagramPacket(sendBuf, 256, address, port);

            try { // send request
                if (DEBUG) {
                    System.out.println("Applet about to send packet to address " + address + " at port " + port);
                }
                socket.send(packet);
                if (DEBUG) {
                    System.out.println("Applet sent packet.");
                }
            } catch (IOException e) {
                System.out.println("Applet socket.send failed:");
                e.printStackTrace();
                return;
            }

            packet = new DatagramPacket(sendBuf, 256);

            try { // get response
                if (DEBUG) {
                    System.out.println("Applet about to call socket.receive().");
                }
                socket.receive(packet);
                if (DEBUG) {
                    System.out.println("Applet returned from socket.receive().");
                }
            } catch (IOException e) {
                System.out.println("Applet socket.receive failed:");
                e.printStackTrace();
                return;
            }

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

        public void actionPerformed(ActionEvent event) {
            int port;

            try {
                port = Integer.parseInt(portField.getText());
                doIt(port);
            } catch (NumberFormatException e) {
                //No integer entered.  Should warn the user.
            }
        }
    }

    //File: quoteApplet.html

    <HTML><TITLE>QuoteClientApplet</TITLE>

    <BODY><APPLET CODE=QuoteClientApplet.class WIDTH=500 HEIGHT=100>
</APPLET>
</BODY>
</HTML>