2

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

3
  • How would a single thread keep track of each stream and block appropriately? This seems like a bad approach. Commented May 3, 2012 at 18:12
  • 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. Commented May 3, 2012 at 18:14
  • Sorry. I did not probably expressed accurately. Question updated. Commented May 3, 2012 at 18:17

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

OK. Thx very much. I was expecting that. It will be more code writing than just calling "BinaryFormatter.Deserialize()" ;)
@Marek yes, it probably will :p

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.