SimpleClientpublic class SimpleClient extends Object Source code from "Java Distributed Computing", by Jim Farley.
Class: SimpleClient
Example: 1-3
Description: A client that uses the simple command-based
protocol to talk to a server. |
Fields Summary |
---|
protected Socket | serverConn | protected SimpleCmdInputStream | inStream |
Constructors Summary |
---|
public SimpleClient(String host, int port)
try {
System.out.println("Trying to connect to " + host + " " + port);
serverConn = new Socket(host, port);
}
catch (UnknownHostException e) {
throw new IllegalArgumentException("Bad host name given.");
}
catch (IOException e) {
System.out.println("SimpleClient: " + e);
System.exit(1);
}
System.out.println("Made server connection.");
|
Methods Summary |
---|
public synchronized void | finalize()
System.out.println("Closing down SimpleClient...");
try { serverConn.close(); }
catch (IOException e) {
System.out.println("SimpleClient: " + e);
System.exit(1);
}
| public static void | main(java.lang.String[] argv)
if (argv.length < 2) {
System.out.println("Usage: java SimpleClient [host] [port]");
System.exit(1);
}
String host = argv[0];
int port = 3000;
try {
port = Integer.parseInt(argv[1]);
}
catch (NumberFormatException e) {}
SimpleClient client = new SimpleClient(host, port);
client.sendCommands();
| public void | sendCommands()
try {
DataOutputStream dout =
new DataOutputStream(serverConn.getOutputStream());
DataInputStream din =
new DataInputStream(serverConn.getInputStream());
// Send a GET command...
dout.writeChars("GET goodies ");
// ...and receive the results
String result = din.readLine();
System.out.println("Server says: \"" + result + "\"");
// Now try a POST command
dout.writeChars("POST goodies ");
// ...and receive the results
result = din.readLine();
System.out.println("Server says: \"" + result + "\"");
// All done, tell the server so
dout.writeChars("DONE ");
result = din.readLine();
System.out.println("Server says: \"" + result + "\"");
}
catch (IOException e) {
System.out.println("SimpleClient: " + e);
System.exit(1);
}
|
|