import java.io.* ;
import java.net.* ;

class Lacze extends Thread
{
    Socket lacze ;

    public Lacze (Socket lacze)
    {
        if (lacze==null) throw new IllegalArgumentException() ;
        this.lacze = lacze ;
    }

    public void run ()
    {
        System.out.println("-- otworzono polaczenie (local port: "+
            lacze.getLocalPort()+" // remote host: "+
            lacze.getInetAddress().getHostName()+" : "+
            lacze.getPort()+") --") ;
        BufferedReader we = null ;
        PrintWriter wy = null ;
        try
        {
            we = new BufferedReader(new InputStreamReader(lacze.getInputStream())) ;
            wy = new PrintWriter(lacze.getOutputStream(),true) ;
            while (true)
            {
                String linia = we.readLine() ;
                if (linia.equals("")) break ;
                wy.println(linia) ;
            }
        }
        catch (IOException ex) {}
        finally
        {
            if (we!=null) try { we.close() ; } catch (IOException ex) {}
            if (wy!=null) wy.close() ;
        }
        try { lacze.close() ; }
        catch (IOException ex) {}
        System.out.println("-- zamknieto polaczenie --") ;
    }
}

class Nasluch extends Thread
{
    ServerSocket nasluch ;

    public Nasluch (ServerSocket nasluch)
    {
        if (nasluch==null) throw new IllegalArgumentException() ;
        this.nasluch = nasluch ;
    }

    public void run ()
    {
        try
        {
            System.out.println("- uruchomiono serwer ECHO na porcie "+SerwerEcho.PORT+" -") ;
            while (true)
            {
                Socket lacze = nasluch.accept() ;
                new Lacze(lacze).start() ;
            }
        }
        catch (SocketException ex) { System.out.println("- zatrzymano serwer ECHO -") ; }
        catch (IOException ex) { System.out.println("- zniszczono serwer ECHO -") ; }
    }
}

public class SerwerEcho
{
    public static final BufferedReader stdwe = new BufferedReader(new InputStreamReader(System.in)) ;
    public static final PrintWriter stdwy = new PrintWriter(System.out,true) ;

    public static final int PORT = 2005 ;

    public static void main (String[] args)
    {
        try
        {
            ServerSocket sluchacz = new ServerSocket(PORT,3) ;
            new Nasluch(sluchacz).start() ;
            try
            {
                for (String kom="" ; !kom.equals("stop") ; kom=stdwe.readLine().trim())
                    System.err.println("wpisz komende \"stop\" aby zatrzymac serwer") ;
            }
            catch (IOException ex) {}
            sluchacz.close() ;
        }
        catch (IOException ex)
        { stdwy.println("nie mozna uruchomic serwera ECHO na porcie "+PORT) ; }
    }
}
