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