package jutil; import java.util.*; import java.io.*; import java.net.*; import jutil.*; /** * Base class for all objects that want to communicate * using a socket. */ public class Correspondent { /** * The socket for this correspondent */ protected Socket sock; /** * Connected to sock's output stream */ protected BufferedReader sockIn; /** * Connected to sock's input stream */ protected PrintWriter sockOut; /** * This constructor does not initialize any fields. Users * must subsequently call initStreams. We need this so the * server can call newInstance. */ public Correspondent() { } /** * Initializes all fields. * @param s the socket to use */ public Correspondent(Socket s) { sock = s; initStreams(); } /** * initializes the reader and writer fields. */ public void initStreams() { try { sockIn = new BufferedReader( new InputStreamReader( sock.getInputStream())); sockOut = new PrintWriter( sock.getOutputStream(), true); } catch(IOException e) { System.err.println(e.getMessage()); } } /** * Closes sock without throwing an exception. */ public void close() { try { sock.close(); } catch(IOException e) { System.err.println(e.getMessage()); } } /** * Initializes sock and other fields by requesting * a connection to a server. * * @param host Internet address of the machine hosting the server * @param port Port of server socket. */ public void requestConnection(String host, int port) { try { sock = new Socket(host, port); initStreams(); } catch(UnknownHostException uhe) { System.err.println("unknown host " + uhe); System.exit(1); } catch(IOException ioe) { System.err.println("failed to create streams " + ioe); System.exit(1); } } /** * Sends a message to the server. This is a non-blocking send. * @param msg the message to be sent */ public void send(String msg) { sockOut.println(msg); } /** * Receives a message from server. This is a blocking receive. * @return the message received. */ public String receive() { String msg = null; try { msg = sockIn.readLine(); } catch(Exception e) { } return msg; } }