Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am about to implement a API for my TCP/IP server written in Java. Right now I have a temporary method that takes a String, executes a command based on the String and returns a String basically like the following.

public void communicate(BufferedReader in, PrintWriter out) {
    while(true) {

private String handleCommand(String command) {
    if (command.equals("command1") {
        // do stuff
        return "Command 1 executed";
    } else if (command.equals("command2") {
        // do some other stuff
        return "Command 2 executed";

I really want to do something more extensible, smarter and stateful, so I could handle more complex and stateful commands and without the method/class getting bloated.

How would you start?

Suggestions, ideas, or links for further reading are very welcome.

share|improve this question
up vote 2 down vote accepted

I'd suggest using an interface, such as:

interface Command {
   public boolean doCommand();

enum CommandNames {

   // other enum stuff

   // Gets a command based on a name
   public static CommandNames getCommand(String name);


Map<CommandNames, Command> commands;

private String handleCommand(String command) {
   Command command = commands.get(CommandNames.getCommand(command));


First draft, but it ought to at least give you some ideas.

share|improve this answer
Enums looks like a good way to go, thank you very much for your suggestion, very helpful :) – Svante Feb 25 '11 at 8:59

The easiest one is thread-per-connection. With flow like:

while (true) {
    accept a connection ;
    create a thread to deal with the client ;
end while

That's good enough even for relatively high traffic.

For extreme performance under very high traffic, you'd rather need event-driven/asynchronous server. These tend to be more complicated, so in that case I'd recommend you to base your solution on existing one, like JBoss' Netty or Apache MINA. Just that you get idea of the performance here, event-driven servers we're designed to combat the C10K problem (10,000+ concurrent client connections).

share|improve this answer
I was rather looking for a smarter API (command handling) implementation. I already have the code for handling the connection initialization. But thanks for you answer :) – Svante Feb 25 '11 at 8:58
I guess I've focused too much on the word "pattern" in title ;-) – vartec Feb 25 '11 at 10:01

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.