简体   繁体   中英

C# order of bytes sent and received by socket

I was wondering about the order of sent and received bytes by/from TCP socket.

I got implemented socket, it's up and working, so that's good. I have also something called "a message" - it's a byte array that contains string (serialized to bytes) and two integers (converted to bytes). It has to be like that - project specifications :/

Anyway, I was wondering about how it is working on bytes: In byte array, we have order of bytes - 0,1,2,... Length-1. They sit in memory.

How are they sent? Is last one the first to send? Or is it the first? Receiving, I think, is quite easy - first byte to appear gets on first free place in buffer.

I think a little image I made nicely shows what I mean.

通过TCP发送

They are sent in the same order they are present in memory. Doing otherwise would be more complex... How would you do if you had a continuous stream of bytes? Wait that the last one has been sent and then reverse all? Or this inversion should work "packet by packet"? So each block of 2k bytes (or whatever is the size of the TCP packets) is internally reversed but the order of the packets is "correct"?

Receiving, I think, is quite easy - first byte to appear gets on first free place in buffer.

Why on the earth the sender should reverse the bytes but the receiver shouldn't? If you build a symmetric system, both do an action or none does it!

Note that the real problem is normally the one of endianness . The memory layout of an int on your computer could be different than the layout of an int of another computer. So one of the two computers could have to reverse the 4 bytes of the int . But endianness is something that is resolved "primitive type" by "primitive type". Many internet protocols, for historical reason, are Big Endian, while Intel CPUs are Little Endians. Even internal fields of TCP are Big Endian (see Big endian or Little endian on net? ), but here we are speaking of fields of TCP, not of the data moved by the TCP protocol.

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