I strongly suspect that the problem here is "framing", meaning: the buffer
that you're processing does not contain exactly one message. It could contain the start of a message, or an entire message and part of the next, either of which can cause problems. TCP is a stream, not a series of messages. The good news is that BinaryFormatter
has framing built in anyway, so honestly: you could just use the NetworkStream
directly and it should just work. Otherwise, you're going to need to implement your own framing layout, and make sure that the receiving code reads an entire frame before processing data and deals correctly with any over-read, i.e. it should retain any bytes that belong to the next frame.
The bad news is that you should not ever use BinaryFormatter
, and in particular you shouldn't use it in a socket server (where the client should always be considered hostile). Further reading.
To investigate whether framing is the problem:
- at the client, log the hex of each message that you're sending
- at the client, log the hex of each message that you're trying to process
- now compare them; they should match message-to-message ("starting the same" isn't enough; they need to be the same length, and identical throughout)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…