// Connection.java -- socket wrapper for text-based IO operations // // author : Scott W. Matey // import java.io.*; import java.net.*; public class Connection extends Object implements Runnable { public Socket socket; InputStream instream; PrintStream outstream; public Thread listener = null; public boolean closed = false; // Initialize with already-opened socket public Connection (Socket s) { socket = s; try { instream = socket.getInputStream (); outstream = new PrintStream (socket.getOutputStream (), true); } catch (Exception e) System.err.println ("Connection() exception:\n" + e); } // Open a new socket on the given host and port public Connection (String host, int port) throws IOException, UnknownHostException { this (new Socket (host, port)); } // Close the socket. public void close () { if (! closed) { if (listener != null) { listener.stop (); listener = null; } try { socket.close (); closed = true; } catch (Exception e) System.err.println ("Connection.close() exception:\n" + e); } } // Write string to socket public void print (String s) { outstream.print (s); outstream.flush (); } // Read line of input from socket public String read () throws EOFException { StringBuffer buff = new StringBuffer (512); int b = 0; do { try { b = instream.read (); } catch (Exception e) System.err.println ("Connection.read() exception:\n" + e); if (b == -1) throw new EOFException(); else buff.append ((char)b); } while (b != '\n'); return buff.toString(); } // Default run method is to listen for input and call notifyInput. // Execution stops when EOF is reached or something closes the connection. public void run () { String s; while (! closed) { try s = read (); catch (EOFException e) { return; } notifyInput (s); } } // Default input notify method ought to be overridden by subclasses. public void notifyInput (String s) { } // Start thread to listen for input on socket. public void listen () { if (listener == null) listener = new Thread (this); listener.start (); } } // end of class Connection