Sign in to follow this  
arcantos9104

How to read the message?

Recommended Posts

arcantos9104    100
Hello all, my first post here, and I'm in a bit of a quandary. I'm working on a multiplayer game, where integers are sent over the network. My question is whether or not 4 bytes will be sent no matter what the number is, and if so would you typecast 4 bytes back to an integer?

Share this post


Link to post
Share on other sites
Sneftel    1788
Quote:
Original post by arcantos9104
My question is whether or not 4 bytes will be sent no matter what the number is
Assuming you send it as a four-byte number, yes.
Quote:
and if so would you typecast 4 bytes back to an integer?
Sure, though you'd want to worry about byte ordering issues.

Share this post


Link to post
Share on other sites
oliii    2196
if you use TCP, be careful as there is the possibility you will receive the 4 bytes integer in a fragmented fashion (for example, the first call of recv() will return the first three bytes, a second call will return you the last byte).

Share this post


Link to post
Share on other sites
Szii    100
Never assume types.

"I sent 4 bytes."
"I read 4 bytes."

But what do those 4 bytes mean? float? 32-bit int? 32-bit uint?

"I send 1 byte type and then 4 bytes"
"I read 1 byte to know how to read the next n bytes"

It's all about your protocol handling.

Obviously if you're going "offset-based" then you can skip the
typing information, but then you kind of limit yourself in terms of flexibility in order to save a few bytes of traffic (which is completely valid in many cases.)
Lots of protocols will have "predefined messages" which specific what offsets are what types.

"I sent a login message of 6 bytes."
"I read 1 byte length, 1 byte login-message-id, 4 bytes uint32 userid and I know how to parse it because we've agreed on what a login message is.

Also, be aware of htons/l() and ntohs/l() variations (byte ordering.)

-Szii

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