C# 通过异步套接字连接发送带有序列化对象的对象大小
我想序列化一个对象并通过网络发送它。我已经使用我的类上的 ISerializeable 属性和 BinaryFormatter 将其设置为将对象转换为字节。我可以发送对象并在接收端反序列化它。但是,为了确保在尝试重建对象之前拥有整个对象,我想将大小与流一起发送。我想将前几个字节设置为大小,检查接收到的数据何时至少达到此固定大小,然后我可以读取该数据并获取对象的完整大小。然后,只需等待我收到的数据等于对象的大小+固定大小的字节即可。如何在流中偏移数据,以便可以发送 int 将对象的大小存储为前几个字节,并将对象的大小存储为剩余字节?
I want to serialize an object and send it over the network. I have set it up using ISerializeable attribute on my class and BinaryFormatter to convert the object to bytes. I can send the object and deserialize it on the receiving end. However, in order to assure that I have the entire object before trying to reconstruct it, I want to send the size along with the stream. I'd like to set the first few bytes as the size, check when the received data is at least this fixed size, then I can read that and get the full size of the object. Then, it's simply a matter of waiting until my received data is the size of the object+ the fixed size bytes. How can I offset my data in my stream so that I can send an int to store the size of the object as the first few bytes, and my object as the remaining bytes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正确的答案是:
从 SocketPacket 读取数据不是的正确方法吗
The right answer is:
Is not the right way to read from a SocketPacket
您可以序列化为
MemoryStream
,然后在完成后添加MemoryStream
中的.Length
,然后添加数据(使用>GetBuffer()
并从数组中复制.Length
字节)。在接收器处倒车;读取长度(通常为 4 个字节),然后将这么多数据打包到MemoeryStream
中;倒带MemoryStream
(Position=0
) 并反序列化。当然,你需要同意字节序等。(看,我什至没有提到prot......哦,另一件事)
Can you just serialize to a
MemoryStream
, then once that is done add the.Length
from theMemoryStream
, followed by the data (useGetBuffer()
and copy.Length
bytes from the array). Reverse at the receiver; read the length (typically 4 bytes), then pack that much data into aMemoeryStream
; rewind theMemoryStream
(Position=0
) and deserialize. Of course, you need to agree endianness etc.(see, and I didn't even mention prot... oh, that other thing)
你究竟想阻止什么? TCP 已经具有内置的一致性和可靠性检查。
What exactly are you trying to prevent? TCP already has built-in consistency and reliability checks.