[英]C# issue with packet in chat application UDP
我正在从http://www.daveoncsharp.com/2009/08/csharp-chat-application-over-asynchronous-udp-sockets-part-1的教程中研究一个聊天应用程序。 但是我有一个问题,任何人都可以为我解释一下,在“包类”中,为什么我们知道“ dataIdentifier”的“字节大小”为4,“名称长度”为4,我看到了包类顶部的描述,但是我不知道为什么。 还有这些:
this.dataIdentifier =(DataIdentifier)BitConverter.ToInt32(dataStream,0); //我们将从dataStream的索引0进行转换,但是它如何结束?
int nameLength = BitConverter.ToInt32(dataStream,4); //为什么我们知道它从4开始?
非常感谢您,我的英语很抱歉。
当您处理网络通信时,必须定义一个“协议”来定义您的“消息”,因为网络连接是基于流而不是基于消息的 。
所以在协议中定义如下
Description -> |dataIdentifier|name length|message length| name | message | Size in bytes -> | 4 | 4 | 4 |name length|message length|
一个int
始终是System.Int32
,一个System.Int32
总是将要存储4个字节(将32除以8,得到4)。
这是另一行,显示每一列的数据类型,也许对您有帮助
Description -> |dataIdentifier|name length|message length| name | message | Size in bytes -> | 4 | 4 | 4 |name length|message length| Data Type -> | int | int | int | string | string |
所以,现在为什么我们在位转换器中跳过4个字节。
让我们将架构备份,但是这次我将减少编号以指示字节数
现在,最后两个是“特殊的”,它们的长度不是像前三个一样的固定长度,它们所做的是从上一列中获取值,即读入了多少个字节。
Description -> |dataIdentifier|name length|message length| name | message | Size in bytes -> | 4 | 4 | 4 | name length | message length | Bytes -> |0 1 2 3 | 4 5 6 7 | 8 9 10 11 | 12 through (12 + name length) | (12 + name length) + 1 through ((12 + name length) + 1 + message length) |
因此,您可以看到读取dataIdentifier
我们从索引0开始并读取4个字节(这是多少BitConverter.ToInt32
将读取)。 然后,当我们想读取nameLength
我们需要从索引4开始,然后再读取4个字节,这就是为什么BitConverter.ToInt32
被传递4(而messageLength
将被传递8)的原因。
如果有不清楚的地方,请在评论中说出来,我将详细说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.