/* File: ThreadedEchoServer.java * * Adapted from an example by * Gary Cornell and Cay S. Horstmann, Core Java (Book/CD-ROM) * */ import java.io.*; import java.net.*; class ThreadedEchoServer { public static void main( String[] args ) { int i = 1; try { ServerSocket s = new ServerSocket( 4882 ); while ( true ) { Socket incoming = s.accept(); System.out.println( "Spawning " + i ); new ThreadedEchoHandler( incoming, i ).start(); i++; } } catch ( Exception e ) { System.out.println( e ); } } } class ThreadedEchoHandler extends Thread { Socket incoming; int counter; ThreadedEchoHandler( Socket i, int c ) { incoming = i; counter = c; } public void run() { try { BufferedReader in = new BufferedReader( new InputStreamReader( incoming.getInputStream() ) ); PrintWriter out = new PrintWriter( incoming.getOutputStream(), true ); out.println( "Hello! Enter BYE to exit." ); // Echo lines back to the client until it sends "BYE" boolean done = false; while ( !done ) { String str = in.readLine(); if ( str == null ) done = true; else { out.println( "Echo (" + counter + "): " + str ); if ( str.trim().equals( "BYE" ) ) done = true; } } incoming.close(); } catch ( Exception e ) { System.out.println( e ); } } }