Async deserialization from TcpClient.GetStream()?

  • Thread starter Thread starter 0to60
  • Start date Start date
0

0to60

I'm using a BinaryFormatter to serialize objects over the NetworkStream of a
TcpClient. I'd like to sit and wait for messages to come in and then
respond accordingly. As far as I know, to do this I have to start a thread
and block on formatter.Deserialize() until a message comes in, then loop
back around and repeat. Basically, I'll always have a thread blocking.

Is there a better way to do this? Ideally, I'd like to do something like
formatter.BeginDeserialize(callBack), but that method doesn't exist.
 
I'd like to use async i/o like you're saying, but I don't know if there's
any way to know how big a serialized object is going to be. I did it that
way on a previous project, but I wasn't using .net serialization. I was
using our own, custom serialization that put the message length in the first
four bytes of a message. That way, you could use async i/o methods to read
in a complete message.

For this project, I don't want to go through the hassle of writing my own,
custom serialization code. Its too bad that .net's built-in serialization
doesn't let you peek the size of the serialized object.



Peter Duniho said:
I'm using a BinaryFormatter to serialize objects over the NetworkStream
of a TcpClient. I'd like to sit and wait for messages to come in and
then respond accordingly. As far as I know, to do this I have to start
a thread and block on formatter.Deserialize() until a message comes in,
then loop back around and repeat. Basically, I'll always have a thread
blocking.

Is there a better way to do this? Ideally, I'd like to do something
like formatter.BeginDeserialize(callBack), but that method doesn't exist.

Without a concise-but-complete code sample showing how exactly you're
sending and receiving the serialized data, it's difficult to suggest
anything.

But, assuming you've got a way of delimiting the serialized objects in the
stream, you could separate the network i/o from the deserialization by
copying the data for each object to a byte[] and then wrapping that in a
MemoryStream for the purpose of deserialization.

Then you can use async i/o to read data and initialize the byte[] for each
object, and a single synchronous call to deserialize each object all at
once, once you've received all the data for it.

Pete
 
Back
Top