import java.io.*; import java.net.*; class ServeOneEcho extends Thread { private Socket socket; private BufferedReader in; private PrintWriter out; public ServeOneEcho(Socket s) throws IOException { socket = s; in = new BufferedReader( new InputStreamReader( socket.getInputStream())); // Enable auto-flush: out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream())), true); start(); // Calls run() } public void run() { try { while (true) { String str = in.readLine(); if (str.equals("END")) break; System.out.println("Echoing: " + str); out.println(str); } System.out.println("closing..."); } catch(IOException e) { System.err.println("IO Exception"); } finally { try { socket.close(); } catch(IOException e) { System.err.println("Socket not closed"); } } } } public class MultiEchoServer { public static void main(String[] args) throws IOException { ServerSocket s = new ServerSocket(0); String ServerPort = s.getLocalPort()+"\n"; System.out.println("Server Started at Port: " + ServerPort); try { while(true) { // Blocks until a connection occurs: Socket socket = s.accept(); try { new ServeOneEcho (socket); } catch(IOException e) { socket.close(); } } } finally { s.close(); } } }