C# Sending size of object with serialized object over Async socket connection
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?
The right answer is:
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
socketData.currentSocket.EndReceive(asyn);
byte[] data = socketData.dataBuffer;
Is not the right way to read from a SocketPacket
MemoryStream resultStream = new MemoryStream();
resultStream.Write(BitConverter.GetBytes(objectStream.Length));
resultStream.Write(objectStream.ToArray());
// send the resultStream
Can you just serialize to a MemoryStream
, then once that is done add the .Length
from the MemoryStream
, followed by the data (use GetBuffer()
and copy .Length
bytes from the array). Reverse at the receiver; read the length (typically 4 bytes), then pack that much data into a MemoeryStream
; rewind the MemoryStream
(Position=0
) and deserialize. Of course, you need to agree endianness etc.
(see, and I didn't even mention prot... oh, that other thing)
What exactly are you trying to prevent? TCP already has built-in consistency and reliability checks.
精彩评论