package dcj.examples;
/**
* 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.
*/
import java.lang.*;
import java.net.*;
import java.io.*;
public class SimpleClient
{
// Our socket connection to the server
protected Socket serverConn;
// The input command stream from the server
protected SimpleCmdInputStream inStream;
public SimpleClient(String host, int port)
throws IllegalArgumentException {
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.");
}
public static void main(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);
}
}
public synchronized void finalize() {
System.out.println("Closing down SimpleClient...");
try { serverConn.close(); }
catch (IOException e) {
System.out.println("SimpleClient: " + e);
System.exit(1);
}
}
} |