C# 读取字节数组
好的,我正在构建服务器<->客户端应用程序。
基本上服务器接收一个包含 header[2bytes]、cryptkeys[2bytes] 和数据的数据包,
我正在考虑构建类以将整个数据包(byte[])加载到其中,然后使用内部类方法处理数据包。现在回答问题。对此最好的方法是什么?我需要能够读取 Int16 Int32 String(int lenght) 并且可能是 float
编辑:有点像 binaryreader 但对于 byte[] 作为输入
Okay so I am building server <-> client application.
Basically server receives a packet that contains header[2bytes], cryptokeys[2bytes],and data
I was thinking about building class to load whole packet (byte[]) into it and then process the packet with inside class methods. Now to the question. What would be best approach to this? I need to be able to read Int16 Int32 String(int lenght) and probably float
Edit: Kinda like binaryreader but for byte[] as an input
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我想说
BinaryReader
是您的最佳选择。根据过去的经验,有时您需要继承 BinaryReader。一个主要示例是当您需要读取以 null 结尾的字符串时,因为 BinaryReader 读取长度前缀的字符串。或者您可以编写自己的类,但最终将提供与 BinaryReader 相同的功能。最后我可能会创建我自己的类。这样,如果您需要更改提取数据的方式,您只需编辑您的类即可。如果您使用 BinaryReader 编写整个项目并意识到您需要添加功能,您将会被搞砸。
I would say
BinaryReader
is your best choice. From past experience there are times where you need to inherit from BinaryReader. A primary example is when you need to read a null-terminated string because BinaryReader reads length-prefixed strings. Or you can write your own class, but you will end up providing the same functionality as BinaryReader.In the end I would probably just create my own class. That way if you need to make changes on how you want to extract the data, you can just edit your class. If you write the entire project with BinaryReader and realize you need to add functionality you will be screwed.
有一个
BitConverter
类。它的静态成员接受字节数组和起始索引并将字节转换为指定的类型。够了吗?There is a
BitConverter
class. Its static members accept a byte array and a starting index and convert the bytes to the specified type. Is it enough?如果这么简单,那么
BinaryReader
通过流,或BitConverter
直接在缓冲区上就足够了;和字符串的编码
。但首先同意字节序;)如果它更复杂并且基于对象,那么我建议使用预装序列化器。编写完整的序列化器并不简单。
您可能还想查看流 API,而不是将其全部加载到内存中 - 对于大型消息来说,这往往会变得昂贵。
If it is that simple, then
BinaryReader
over the stream, orBitConverter
directly on the buffer should suffice; andEncoding
for strings. But agree endianness first ;)If it is more complex and object-based, then I suggest using a pre-canned serializer. Writing a full serializer is not trivial.
You might also want to look at a streaming API rather than loading it all into memory - that tends to get expensive for large messages.
为什么不使用 Stream,例如 NetworkStream?
Why not use a Stream, for instance a NetworkStream?