/****************************************************************************** * Compilation: javac EchoConnection.java * Dependencies: In.java Out.java * * Echoes lines back to one client, in a separate thread. * ******************************************************************************/ import java.io.IOException; import java.net.Socket; public class EchoConnection extends Thread { private final Socket socket; public EchoConnection(Socket socket) { this.socket = socket; } public void run() { try { // open up IO streams for this client In in = new In(socket); Out out = new Out(socket); // read each line and echo it back to the same client String s; while ((s = in.readLine()) != null) { out.println(s); } out.close(); in.close(); } finally { // close the socket even if an exception occurs System.err.println("Closing connection with client"); try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }