import java.net.*; import java.io.*; public class CommentsClient { public static final int DEFAULT_PORT = 7777; private static final String QueryString = "query"; private static final String InsertString = "insert"; private int port = 0; private String host = null; private OutputStream os = null; public CommentsClient (String host, int port, OutputStream os) { this.host = host; this.port = ((port == 0) ? DEFAULT_PORT : port); this.os = os; query(); } public CommentsClient (String host, int port, OutputStream os, String name, String username, String comments) { this.host = host; this.port = ((port == 0) ? DEFAULT_PORT : port); this.os = os; insert(name, username, comments); } private void query () { PrintWriter out = new PrintWriter (os, true); try { Socket s = new Socket (host, port); ObjectOutputStream oos = new ObjectOutputStream (s.getOutputStream()); oos.writeObject (QueryString); oos.flush(); BufferedReader in = new BufferedReader (new InputStreamReader (s.getInputStream())); String line; while ((line = in.readLine()) != null) { out.println (line); } oos.close(); s.close(); } catch (IOException e) { out.println ("Error querying." + e); return; } } private void insert (String name, String username, String comments) { PrintWriter out = new PrintWriter (os, true); try { Socket s = new Socket (host, port); ObjectOutputStream oos = new ObjectOutputStream (s.getOutputStream()); oos.writeObject (InsertString); oos.writeObject (name); oos.writeObject (username); oos.writeObject (comments); oos.flush(); BufferedReader in = new BufferedReader (new InputStreamReader (s.getInputStream())); String line; while ((line = in.readLine()) != null) { out.println (line); } oos.close(); s.close(); } catch (IOException e) { out.println ("Error inserting." + e); return; } } public static void main (String args[]) { if (args.length == 0) { CommentsClient cc = new CommentsClient ("localhost", 0, System.out); } else if (args.length == 3) { CommentsClient cc = new CommentsClient ("localhost", 0, System.out, args[0], args[1], args[2]); } } }