Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to implement protocols?

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.

like image 903
fluffels Avatar asked Oct 30 '08 07:10

fluffels


1 Answers

State Machines

To my mind, a state machine is the easiest way to model and handle protocols. A state would be reached by several transitions relating to valid commands received. Each state would then allow only a certain subset of commands.

State machines are used in compiler construction for lexical analysis of a program. I see the problem of protocol implementation as a special case of this.

like image 154
fluffels Avatar answered Nov 15 '22 02:11

fluffels