EchoConnection.java


Below is the syntax highlighted version of EchoConnection.java from §8.4 Operating Systems.


/******************************************************************************
 *  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();   }
        }
    }
}


Copyright © 2000–2025, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Nov 13 05:59:16 PM EST 2026.