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