Java Reference
In-Depth Information
Example 5•9: Server.java (continued)
try {
service = (Service)serviceClass.newInstance();
}
catch (NoSuchMethodError e) {
throw new IllegalArgumentException(
"Service must have a " +
"no-argument constructor");
}
int port = Integer.parseInt(t.nextToken());
// If no exceptions occurred, add the service
server.addService(service, port);
out.print("SERVICE ADDED\n");
// acknowledge
}
}
else if (command.equals("remove")) { // Remove service
if (!authorized) out.print("PASSWORD REQUIRED\n");
else {
int port = Integer.parseInt(t.nextToken());
server.removeService(port); // remove the service
out.print("SERVICE REMOVED\n"); // acknowledge
}
}
else if (command.equals("max")) { // Set connection limit
if (!authorized) out.print("PASSWORD REQUIRED\n");
else {
int max = Integer.parseInt(t.nextToken());
server.setMaxConnections(max);
out.print("MAX CONNECTIONS CHANGED\n");
}
}
else if (command.equals("status")) { // Status Display
if (!authorized) out.print("PASSWORD REQUIRED\n");
else server.displayStatus(out);
}
else if (command.equals("help")) { // Help command
// Display command syntax. Password not required
out.print("COMMANDS:\n" +
"\tpassword <password>\n" +
"\tadd <service> <port>\n" +
"\tremove <port>\n" +
"\tmax <max-connections>\n" +
"\tstatus\n" +
"\thelp\n" +
"\tquit\n");
}
else if (command.equals("quit")) break; // Quit command.
else out.print("UNRECOGNIZED COMMAND\n"); // Error
}
catch (Exception e) {
// If an exception occurred during the command, print an
// error message, then output details of the exception.
out.print("ERROR WHILE PARSING OR EXECUTING COMMAND:\n" +
e + "\n");
}
}
// Finally, when the loop command loop ends, close the streams
// and set our connected flag to false so that other clients can
// now connect.