2
votes

I have really simple TcpListener + TcpClient slient-server application. I accept incomming connections async. Then I read data from network stream.

I run this code in new thread. but I have to run new thread for each client...

while (true)
    (MyCoreMessage)BinaryFormatter.Deserialize(TcpClient.GetStream())

Is there some (easy and simple) async way to desearialize object from networkstream? Not creating new thread per clent...

thanks for help

1
How would a single thread keep track of each stream and block appropriately? This seems like a bad approach.Tejs
What you are asking does not make sense to me. You can't read from a single NetworkStream on multiple threads anyway? What does have async to do with this? Just open a new thread per connection.usr
Sorry. I did not probably expressed accurately. Question updated.Marek Javůrek

1 Answers

2
votes

I would strongly suggest that you preceded the data with a length-prefix (for example, as network-byte-order 4 bytes), and read this length first. Then you know how much data to expect in the next frame, so buffer that much data using async reads (assuming the size isn't too silly large). When you have finished buffering the data (async), then you can use something like MemoryStream and deserialize normally.

This:

  • allows proper framing
  • allows you to sanity check the length
  • allows you to do all the network access as async
  • allows you to only involve the deserializer when you know you have sensible data