如何实现网络协议? [英] How to implement a network protocol?

查看:219
本文介绍了如何实现网络协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个通用问题。我不是在寻找最好的答案,我只是想让你表达你最喜欢的做法。

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

我想在Java中实现一个网络协议(但这是一个相当普遍的问题,我在C ++中面临同样的问题),这不是第一次,我以前做过这个。但我想我缺少一个好的方法来实现它。实际上通常是关于在主机之间交换文本消息和一些字节缓冲区,存储状态并等待下一个消息到来。问题是,我通常最终得到一堆开关和或多或少复杂if语句对不同的状态/消息作出反应。整个事情通常很复杂,很难说。更何况,有时出现的有一些盲点,我的意思是协议的状态,没有被覆盖,并以不可预测的方式表现。我试图写下一些状态机类,它照顾检查每个动作的开始和结束状态以或多或少的智能方式。这使得编程协议非常复杂,因为我必须编写行和代码行以涵盖所有可能的情况。
我想要的是一个像一个好的模式,或一个最佳实践,用于编程复杂的协议,容易mantain和扩展和非常可读。

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.

您的建议是什么?

推荐答案

strong> State 设计模式,以了解如何避免大量的switch语句。

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.

这篇关于如何实现网络协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆