import java.io.*;
import java.net.*; 

class ClientHandler extends Thread {

  protected Socket incoming; 

  public ClientHandler(Socket incoming) {
    this.incoming = incoming;
  }

  public void run() {
    try {
      BufferedReader in 
        = new BufferedReader(new InputStreamReader(incoming.getInputStream())); 
      PrintWriter out 
        = new PrintWriter(new OutputStreamWriter(incoming.getOutputStream())); 
      out.println("Hello! This is Java MultiEchoServer.");
      out.println("Enter BYE to exit."); 
      out.flush();
      
      for (;;) {
        String str = in.readLine(); 
        if (str == null) {
          break; 
        } else {
          out.println("Echo: " + str);
          out.flush(); 
          System.out.println("Received: " + str);
          
          if (str.trim().equals("BYE")) 
            break; 
        }
      }
      incoming.close(); 
    } catch (Exception e) {
      System.out.println("Error: " + e); 
    }
  }

}

public class MultiEchoServer {

  public static void main(String[] args) {
    System.out.println("MultiEchoServer started."); 
    
    try {
      ServerSocket s = new ServerSocket(8009); 
      for (;;) {
        Socket incoming = s.accept(); 
        new ClientHandler(incoming).start(); 
      }
    } catch (Exception e) {
      System.out.println("Error: " + e); 
    }

    System.out.println("MultiEchoServer stopped."); 
  }
}