import java.io.*; import java.net.*; /** ThreadedEchoServer.java This program implements a multithreaded server that listens to port 8189 and echoes back all client input. */ public class ThreadedEchoServer { public static void main(String[] args ){ try{ long i = 1; ServerSocket s = new ServerSocket(8189); for (;;){ Socket incoming = s.accept( ); System.out.println("Spawning " + i); Thread t = new ThreadedEchoHandler(incoming); t.start(); i++; } } catch (Exception e) { e.printStackTrace(); } } } /** This class handles one client input. */ class ThreadedEchoHandler extends Thread { public ThreadedEchoHandler(Socket i) { incoming = i; } public void run() { try { BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); out.println( "Hello! Enter BYE to exit." ); boolean done = false; while (!done) { String str = in.readLine(); if (str == null) done = true; else { out.println("Echo = "+str); if (str.trim().equals("BYE")) done = true; } } incoming.close(); } catch (Exception e) { e.printStackTrace(); } } private Socket incoming; }