简体   繁体   English

套接字发送和接收的C#字节顺序

[英]C# order of bytes sent and received by socket

I was wondering about the order of sent and received bytes by/from TCP socket. 我想知道TCP套接字发送/接收字节的顺序。

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. 无论如何,我想知道它如何处理字节:在字节数组中,我们具有字节顺序-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"? 因此,每个2k字节的块(或TCP数据包的大小)在内部都被反转了,但是数据包的顺序是“正确的”吗?

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. 一个的内存布局int您的计算机上可能会比一个的布局不同int另一台计算机。 So one of the two computers could have to reverse the 4 bytes of the int . 因此,两台计算机之一可能不得不反转int的4个字节。 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. 由于历史原因,许多互联网协议都是Big Endian,而Intel CPU是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. 甚至TCP的内部字段都是Big Endian(请参见net上的Big endian还是Little endian? ),但是在这里,我们所说的是TCP的字段,而不是TCP协议移动的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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