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

public class BetterEchoServer
{
    public static final int    ECHO_PORT   = 3737;

    public static void main( String [] args )
    {
        ServerSocket ss = null;
        try
        {
            ss = new ServerSocket( ECHO_PORT );

            while( true )
            {
                Socket sock = ss.accept( );
                Thread t = new EchoHandler( sock );
                t.start( );
            }
        }
        catch( IOException e )
        {
            System.out.println( e );
        }
        finally
        {
            try { if( ss != null ) ss.close( ); }
            catch( IOException e ) { }
        }
    } 
}

class EchoHandler extends Thread
{

    public static final String EXIT_STRING = "***";
    private Socket sock;

    public EchoHandler( Socket incoming )
    {
        sock = incoming;
    }
 
    public void run( )
    {
        try
        {
            InputStreamReader in = new InputStreamReader( sock.getInputStream( ) );
            BufferedReader is = new BufferedReader( in );
            PrintWriter os = new PrintWriter( sock.getOutputStream( ), true ); // Autoflush 

            os.println( "Welcome to the RudeEchoServer!" );
            os.println( "Enter " + EXIT_STRING + " to exit" );

			System.out.println( "Connected from " + sock.getInetAddress( )
                                            + ":" + sock.getPort( ) );
            
            String str;

            while( ( str = is.readLine( ) ) != null )
            {
                if( str.trim( ).equals( EXIT_STRING ) )
                    break;
                os.println( str.toUpperCase( ) );
            }
        }
        catch( IOException e )
        {
            System.out.println( e );
        }
        finally
        {
        	
            try { if( sock != null ) sock.close( ); }
            catch( IOException e ) { System.out.println( e ); }
        }
    }
}

