1 /* File: ThreadedEchoServer.java 2 * 3 * Adapted from an example by 4 * Gary Cornell and Cay S. Horstmann, Core Java (Book/CD-ROM) 5 * 6 */ 7 8 import java.io.*; 9 import java.net.*; 10 11 class ThreadedEchoServer 12 { public static void main( String[] args ) 13 { int i = 1; 14 try 15 { ServerSocket s = new ServerSocket( 4882 ); 16 17 while ( true ) 18 { Socket incoming = s.accept(); 19 System.out.println( "Spawning " + i ); 20 new ThreadedEchoHandler( incoming, i ).start(); 21 i++; 22 } 23 } 24 catch ( Exception e ) 25 { System.out.println( e ); 26 } 27 } 28 } 29 30 class ThreadedEchoHandler extends Thread 31 { 32 Socket incoming; 33 int counter; 34 35 ThreadedEchoHandler( Socket i, int c ) 36 { incoming = i; counter = c; } 37 38 public void run() 39 { try 40 { BufferedReader in = 41 new BufferedReader( 42 new InputStreamReader( incoming.getInputStream() ) ); 43 PrintWriter out = 44 new PrintWriter( incoming.getOutputStream(), true ); 45 46 out.println( "Hello! Enter BYE to exit." ); 47 48 // Echo lines back to the client until it sends "BYE" 49 boolean done = false; 50 while ( !done ) 51 { String str = in.readLine(); 52 if ( str == null ) done = true; 53 else 54 { out.println( "Echo (" + counter + "): " + str ); 55 56 if ( str.trim().equals( "BYE" ) ) 57 done = true; 58 } 59 } 60 incoming.close(); 61 } 62 catch ( Exception e ) 63 { System.out.println( e ); 64 } 65 } 66 }