ChatConnection.java


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


/******************************************************************************
 *  Compilation:  javac ChatConnection.java
 *
 ******************************************************************************/

import java.io.IOException;
import java.net.Socket;

public class ChatConnection extends Thread {
    private Socket socket;
    private Out out;
    private In in;
    private String message;     // one line buffer

    public ChatConnection(Socket socket) {
        this.socket = socket;
    }

    public void println(String s) { out.println(s); }

    public void run() {
        try {
            // open up IO streams for this client
            in  = new In(socket);
            out = new Out(socket);
            String s;
            while ((s = in.readLine()) != null) {
                setMessage(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();   }
        }
    }


   /***************************************************************************
    *  The methods getMessage() and setMessage() are synchronized
    *  so that the thread in Connection doesn't call setMessage()
    *  while the ChatConnectionListener thread is calling getMessage().
    ***************************************************************************/
    public synchronized String getMessage() {
        if (message == null) return null;
        String temp = message;
        message = null;
        notifyAll();
        return temp;
    }

    public synchronized void setMessage(String s) {
        if (message != null) {
            try                  { wait();               }
            catch (Exception ex) { ex.printStackTrace(); }
        }
        message = s;
    }

}


Copyright © 2000–2025, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Nov 13 06:04:11 PM EST 2026.