Sign in to follow this  

[C#] Packets using marshalled structs

Recommended Posts

Consider the following class definition and its methods:

[code]public class Packet

static virtual Packet FromBuffer();
NetBuffer ToBuffer();


Right now, I construct each packet like this and manually write each value to a byte buffer.

I read in the FAQ when I arrived at here the use of marshalled structures. Should I potentially swap over to serialized versions of these?
I initially used serialized objects but the overhead for each packet was immense (100+ bytes, ouch). Packets that are constructed from structs are much smaller.

Main reasons to swap over:

*Objects have a higher allocation cost than structs? (stack vs heap)?
*Structs have automatic serialization advantage

Any other advantages? Disadvanages? Why should I do it / not?

Share this post

Link to post
Share on other sites
[quote name='hplus0603' timestamp='1329960570' post='4915734']
That "static virtual" looks interesting. What language is that?
Java#.Org :P

To the op:
So have a method of the packet that takes a binarywriter or binaryreader. It can then read/write its self out to the buffer. If you want you could encapsulate that whole thing up into another object, call it "packet serializer" and simply use reflection to serialize the members out. Pretty simple.

Share this post

Link to post
Share on other sites
For a game? I would suggest not using struct serialization and instead serialize your events manually allowing your objects to be "(de)serialize themselves". As an introduction you could [url=""]read this[/url] though you might already understand a lot of the concepts. I know HPlus and others sometimes reference the [url=""]visitor pattern[/url] if you don't want to have our class implement say a serializable interface with serialize and deserialize methods. There's a few ways to do it.

For a game I don't much care for the struct serialization system as it's a kind of roundabout way to serializing things. Just serialize what you want directly without introducing structs. And also reflection in my experience isn't that great except for very basic networking in a game. Often you want to serialize things and you'll find the default reflection method is very verbose especially if you only want to serialize what's changed. (You can try implementing your own attribute system for controlling such things, but I haven't had much success with a sane design).

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this