import java.io.*; import java.net.*; import java.util.*; public class ChatClient { public static final int CHAT_PORT = 3737; public static final String EXIT_STRING = "LOGOUT"; public static void main( String [] args ) { Socket s = null; if( args.length != 1 ) { System.out.println( "Usage: ChatClient servername" ); return; } try { s = new Socket( args[ 0 ], CHAT_PORT ); // Start the listening thread Thread t = new GetIncoming( s ); t.start( ); // Main thread reads from user, and sends to server InputStreamReader in = new InputStreamReader( System.in ); BufferedReader is = new BufferedReader( in ); PrintWriter os = new PrintWriter( s.getOutputStream( ), true ); // Autoflush String str; while( ( str = is.readLine( ) ) != null ) { if( str.trim( ).equals( EXIT_STRING ) ) break; os.println( str ); } } catch( Exception e ) { System.out.println( e ); } finally { try { if( s != null ) s.close( ); } catch( IOException e ) { System.out.println( e ); } } } } class GetIncoming extends Thread { private Socket incoming; public GetIncoming( Socket sock ) { incoming = sock; } public void run( ) { try { InputStreamReader in = new InputStreamReader( incoming.getInputStream( ) ); BufferedReader is = new BufferedReader( in ); String str; while( ( str = is.readLine( ) ) != null ) System.out.println( str ); } catch( java.net.SocketException e ) { System.out.println( "Connection terminated" ); } catch( IOException e ) { System.out.println( e ); } finally { try { if( incoming != null ) incoming.close( ); } catch( IOException e ) { System.out.println( e ); } } } }