简体   繁体   English

处理数据包的设计模式

[英]Design pattern for handling packets

I'm writing a TCP Network for a game project. 我正在为游戏项目编写TCP网络。 When a packet comes in the first byte of the packet determines that packet's handling type. 当数据包进入时,数据包的第一个字节确定该数据包的处理类型。 The packet should than be forwarded on to a method that handles the packet based on its handle type 然后,应将数据包转发到根据其句柄类型处理数据包的方法

I could have a bunch of logic cases that then call a method based on the packet type, but I wanted to see what better design patterns I could implement to reduce code duplication. 我可以有很多逻辑案例,然后根据数据包类型调用方法,但是我想看看我可以实现哪些更好的设计模式来减少代码重复。

I've thought about using the subscriber/notifier pattern already, I'm not fully against it, but I feel as if I'd have a bunch of Subscribe(packetType, funcReference) calls, so perhaps it isn't ideal either. 我已经考虑过使用订阅者/通知者模式,我并不完全反对它,但是我感觉好像要进行一堆Subscribe(packetType,funcReference)调用,因此也许也不理想。

Having a big switch statement that handles each packet type is perfectly acceptable. 具有处理每种数据包类型的大switch语句是完全可以接受的。 Even in the case where there's multiple resolvers for a given handled packet, you can just trigger the subscribed callbacks in that case. 即使在给定处理的数据包有多个解析程序的情况下,您也可以在这种情况下触发已订阅的回调。

In my experience this is one of those cases where people (myself included, in the past) will over-complicate for the sake of what feels like "better" code. 根据我的经验,这是人们(过去包括我自己)为了“更好”的代码而变得过于复杂的情况之一。 Switch then handle is very easy to grok at first glance, and easy to extend. 乍看之下,先开关后手柄非常容易,并且易于扩展。

Since your packet type marker is only a byte, you can make an array of pointers to handling functions with size of 256 elements. 由于您的数据包类型标记仅是一个字节,因此您可以创建一个指针数组来处理大小为256个元素的函数。 Initialize it once upon program start. 程序启动后初始化一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM