package TcpExamples;

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

/**
 * Handles all the logic associated with one connection
 * by running in a thread of its own. This is the server
 * portion as well, so we artificially invent what happens
 * if the server can't respond to a connection for 10 sec.
 * 
 * @author Don McGregor
 */

public class TcpExample4HandlerThread extends Thread
{
    /** The socket connection to a client */
    Socket socket;
    
    /** The thread constructor creates the socket from
     * a ServerSocket, and passes one to the thread
     * responsible for handling the connection.
     * 
     * @param socket The socket connection handled by this thread
     */
    public TcpExample4HandlerThread(Socket socket)
    {
        this.socket = socket;
    }
    
    /** Handles one connection. We add an artificial slowness
     * to handling the connection with a sleep(). This means
     * the client won't see a server connection response for ten seconds (default).
     */
	// @overriding run() method in Java Thread class is deliberate
	@Override 
    public void run()
    {
        try
        {
            System.out.println("TcpExample4HandlerThread starting to handle a thread...");
            // get the connection output stream, then wait a period of time. 
             OutputStream os = socket.getOutputStream();
              PrintStream ps = new PrintStream(os);

			 final long TIMEOUT = 2000; // 2000 milliseconds = 2 seconds, 10000 milliseconds = 10 seconds
			 System.out.println("TcpExample4HandlerThread pausing for TIMEOUT=" + TIMEOUT + "ms"); // debug
             Thread.sleep(TIMEOUT); // 10 seconds
                
            ps.println("This message was written by the server TcpExample4HandlerThread");
            ps.flush();
            socket.close();
            System.out.println("TcpExample4HandlerThread finished handling a thread, now exit.");
        }
        catch(IOException | InterruptedException e) // either a networking or a threading problem
        {
            System.out.println("Problem with TcpExample4HandlerThread networking:"); // describe what is happening
            System.out.println("Error: " + e);
            // Provide more helpful information to user if exception occurs due to running twice at one time
            if (e instanceof java.net.BindException)
                System.out.println("*** Be sure to stop any other running instances of programs using this port!");
        }
    }
}