The more object oriented approach would be to define an interface or class, Command (extends / implements Serializable). These have one method for executing the command on the server. In pseudo code:
You construct command objects and send these using ObjectOutputStream and receive them using ObjectInputStream. The Command class / interface could have multiple sub classes, one for each command you want to support. For instance you could have a RegisterCommand, SignInCommand, QuitCommand, MessageCommand (for regular messages). You can then use a factory method for constructing commands from Strings:
The server then retrieves one command at a time, and invokes its execute method on the server. The command will then know what to do. In pseudo code:
As said in my first piece of code, execute probably needs a parameter of type ChatServer, as it will need to call a method on this: register(
String, String, String), login(String, String), quit(), etc. An example:
There may be less intricate designs, but this is probably the easiest to extend with new commands. All you need to do is:
- add the necessary method to the ChatServer
- add another Command implementation that calls this method
- modify the CommandFactory to recognize this command
You can use a similar design for responses back to the client. Types of responses can be "nick already exists" (for registering), "login failed", or "succeeded". The easiest type of response is a simple enum, or even easier a String indicating only the response message.
The protocol then changes slightly. First of all, Command.execute gets a return type:
The protocol:
This is not much more than a simple ping-pong protocol: the client sends a command (or request) to the server, and the server sends back a response, until either one quits.