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

package example;

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;

/**
 * Handles a single connection with a client.
 */
public class Handler implements Runnable {
    /** the Socket connection to the client */
    private Socket sock;
    
    /**
     * Creates a new instance of Handler.
     * @param sock the Socket connection to the client, as returned by
     * SocketServer.accept().
     */
    public Handler(Socket sock) {
        this.sock = sock;
        new Thread(this).start();
    }

    /**
     * Handle incoming communication.
     */
    public void run() {
        try {
            // pull the streams from the socket
            InputStream is = sock.getInputStream();
            OutputStream os = sock.getOutputStream();
            // cast the streams to something appropriate.  Always start
            // with the output stream.
            BufferedReader br =
                    new BufferedReader(new InputStreamReader(is));
            PrintStream ps = new PrintStream(os);

            // normally, the handler would continously listen for messages.
            // here, we just get a single line.
            String line = br.readLine();
            ps.print("You said, '"+line+"'\r\n");
            
            // don't close the socket until you're done.
            sock.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    
}