Say you are writing an application that must implement the HTTP protocol. Protocols are quite complex and may allow several commands depending on which stage of a transaction they are in.
As an example, look at SMTP. An SMTP server must throw an error if the "data" command is sent before receiving "rcpt" and "mail".
My question is: what is the best way to handle protocols such as this in code? Are there any design patterns related to this?
Edit: This question relates to the theory behind implementing protocols. I'm aware that using a library is the best approach in practise.