简体   繁体   中英

Design pattern for handling packets

I'm writing a TCP Network for a game project. 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.

Having a big switch statement that handles each packet type is perfectly acceptable. 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. Initialize it once upon program start.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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