title: Generic Architecture for a Network Server/Client using a State Machine
body: <p>All,</p>
  
  <p>so, I <strike>invented</strike>made up a simple protocol that I want to use for a client to talk to a server.  It's the typical (I think) three-phase layout:</p>
  
  <ul>
  <li>Connection Establishment (will eventually include capability negotiation)</li>
  <li>Actual Data Exchange - packets are happily travelling to and fro', get interpreted by the respective receiver which acts on them accordingly</li>
  <li>Connection Teardown - one side says "don't wanna no more', other side says 'so be it' (will eventually allow the other side to send some data until it is done instead of simply closing the conversation)</li>
  </ul>
  
  <p>The framework is a simple setup:  The server does java.net.ServerSocket.accept() and starts a thread to handle the incoming connection by a client, which creates a java.net.Socket() to the host/port where the server is waiting.  Both sides use the java.io.InputStream and java.io.OutputStream and spew data at each other, assembling outgoing and parsing incoming messages.  Fine, so far.</p>
  
  <p>So far, the protocol is hard-coded. Connection Establishment and Teardown are pretty much ok, while the Data Exchange part - which I want to be full-duplex - is pretty much a mess.  </p>
  
  <p>So, thinks me, let's do this the good way and set up a state machine using, surprise, the design pattern of the same name.  I'm pretty clear about what the states should be for the server and the client, respectively, and what kinds of events should happen for a transition to take place, and what actions should be undertaken when a transition does happen. That looks <i>good</i> - on paper, that is.  In practice, I've stubmled over a couple of questions that I can't solve on paper.  </p>
  
  <p>In particular, the inputs of the state machine are ... a little diverse.  How could I possibly be able to write data, read data and check the connection (it might have closed or may be broken) at the same time?  Also, the 1st and 3rd phase should get timers to avoid potentially infinite waiting times for answers.</p>
  
  <p>So, I'd be grateful for any help that bridges my gap between the theory state machine and the code state machine.</p>
  
  <p>BTW, I can read C/C++/C# too - no need to translate to Java (which is what I'm using).</p>