/Users/mw17785/Projects/gamefinder/gamefinder/trunk/src/example/Client.java
/*
 * Client.java
 */

package example;

import cs101.comm.Announcer;
import cs101.comm.GameInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;

/**
 * An example Client communicator that uses the gamefinder Announce
 * class to find an appropriate server.
 */
public class Client {
    /** the socket this client uses to talk to the server */
    Socket sock;
    
    
    /** Creates a new instance of Client */
    public Client() {
        try {
            // we need to figure out where the server is.  Go ask Announcer.  
            GameInfo gi = Announcer.find("SocketTest");
            
            if (gi == null) {
                // Announcer.find returns null when the user cancels the search.
                System.out.println("Cancelled");
                return;
            }
            // diagnostics (you don't need this unless you're debugging
            System.out.println("Found "+gi.getDescription()+" at "+
                    gi.getHostName()+" on port "+gi.getPort());
            
            // create a socket to the server we found
            sock = new Socket(gi.getHostName(), gi.getPort());
            
            // get the input and output streams.  Always get the output stream
            // first.
            OutputStream os = sock.getOutputStream();
            InputStream is = sock.getInputStream();

            // turn the streams into something more appropriate.  This
            // could ObjectStreams, DataStreams or Readers/Writers.
            PrintStream ps = new PrintStream(os);
            BufferedReader br = 
                    new BufferedReader(new InputStreamReader(is));

            // you can write anything to the output stream at any time --
            // but make sure that only one thread can be writing to the
            // stream at a time!
            ps.print("Hello there\r\n");
            
            // ordinarily, you'd have a separate thread that continually
            // listens to the input stream and does something appropriate
            // for each message.  We'll leave that to you to figure out.
            String line = br.readLine();
            System.out.println(line);
            
            // don't close the socket until you're completely done.
            sock.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        new Client();
    }
}