Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a network protocol?

Here is a generic question. I'm not in search of the best answer, I'd just like you to express your favourite practices.

I want to implement a network protocol in Java (but this is a rather general question, I faced the same issues in C++), this is not the first time, as I have done this before. But I think I am missing a good way to implement it. In fact usually it's all about exchanging text messages and some byte buffers between hosts, storing the status and wait until the next message comes. The problem is that I usually end up with a bunch of switch and more or less complex if statements that react to different statuses / messages. The whole thing usually gets complicated and hard to mantain. Not to mention that sometimes what comes out has some "blind spot", I mean statuses of the protocol that have not been covered and that behave in a unpredictable way. I tried to write down some state machine classes, that take care of checking start and end statuses for each action in more or less smart ways. This makes programming the protocol very complicated as I have to write lines and lines of code to cover every possible situation. What I'd like is something like a good pattern, or a best practice that is used in programming complex protocols, easy to mantain and to extend and very readable.

What are your suggestions?

like image 306
gotch4 Avatar asked Mar 15 '10 20:03

gotch4


1 Answers

Read up on the State design pattern to learn how to avoid lots of switch statements.


"sometimes what comes out has some "blind spot", I mean statuses of the protocol that have not been covered..."

State can help avoid gaps. It can't guarantee a good design, you still have to do that.

"...as I have to write lines and lines of code to cover every possible situation."

This should not be considered a burden or a problem: You must write lines of code to cover every possible situation.

State can help because you get to leverage inheritance. It can't guarantee a good design, you still have to do that.

like image 69
S.Lott Avatar answered Sep 21 '22 05:09

S.Lott