I'm working on a client application that sends and receives commands (Strings) over a Socket. I have some difficulties with the command-handling however.
The problem is as follows: There are two types of commands: * commands that we have to send to the server, and then wait for a reply. The Thread that sent the command must stop meanwhile, like 'blocking I/O'. The replies must be passed back to the code that sent the command. * commands that can be sent to us, without having asked for them (like an asynchronous connection). The server can send them at any time. These commands must be passed to a sort of 'Listener', that can handle them.
The order the commands arrive is completely random (for example, a asynchronous command can arrive between another command and it's 'answer'). Also, two Threads must be able to 'send and wait for a reply' at the same moment, without receiving the wrong answer. I have methods for reading exactly one command from a stream, and for recognizing which commands and replies match.
What is the best (and most stable) way to implement this in Java? Can the new I/O classes be used to improve this?