How's my packet architecture

Started by
2 comments, last by KevinLee 18 years ago
I am curious if the architecture I put together for my packet sending/receiving is a good one for a large scale online game. I am not very experienced at network programming so any input is greatly appreciated. This is what I do: For each packet I send I do this: 1) I create a byte array that contains: a) An integer that states the type of packet (more on this later) b) An integer that contains the length of the packet c) I then take a class packet object and serialize it into the byte array 2) I then send the byte array through a NetworkStream object using C#. The “type of packet” indicates which class object is used for the packet. I create a separate class for each packet type. For example: public class PacketMove() –> Packet sent when a player moves public class PacketSay() –> Packet sent when a player says something public class PacketExit –> Packet sent when a player exits the game. Etc... 3) The server then uses NetworkStream to receive this packet. The problem is that the server gets the packet type and then must do a huge switch or if statement to know which type of object to create. For example: // Read the bytes and deserialize them into a object that is one of the packet classes object packet = ReadPacket(stream, ref packetType); If(packetType == PacketType.Move) { PacketLogin packetMove = (PacketLogin) packet; } else if(packetType == PacketType.Say) { PacketSay packetSay = (PacketSay) packet; … } Etc… Is this how it’s normally done? Thank in advanced.
Advertisement
Correct, in terms of network IO and programming C/C++ derivative at the most simplistic approach.

Kuphryn
Yes, you can do something like that. Note that I would call it a packet "structure" or "approach" rather than "architecture."

You could easily improve the handling on the receiving end by using a hashtable or other look-up from "packet type" to "packet handler object", where you create a packet handler object per packet type, and make that object responsible for de-serializing and dispatching the packet.

For packets of unknown type, you probably want to call out to some "hook" function (to allow user extension), and then just skip past the data, which you can do because you have a packet length field in the packet.
enum Bool { True, False, FileNotFound };
This is so called TLV.

---------
TLV
---------
Type
Length
Value
---------

So, read/send your TLV to a chain, then dispatch this TLVs into your program. Like a message chain.

This topic is closed to new replies.

Advertisement