C# TcpClient reading multiple messages over persistent connection

泄露秘密 提交于 2019-12-06 11:55:59

The way you read 4 or 8 bytes is wrong. You need to loop until you actually got them. You might get 1.

You are assuming here and in other places that you will read the amount that you wanted. You will read at least one byte, or zero if the connection was shut down by the remote side.

Probably, you should use BinaryReader to abstract away the looping.

Also, you need to clean up resources. Why aren't you wrapping them in using? All the Close calls are unsafe and not needed.

Also I don't see why exceptions for control flow would be necessary here. Refactor that away.

Just 2 thoughts that hopefully help improving your code but are no answer to your initial question:

  • You are sending 8 bytes indicating the following payload length but use only 4 of them in the following BitConverter.ToInt32 call, so 4 bytes would be enough.
  • What would happen if the transmission is cut of from the other side? In my opinion you have no way to determine that the data you have receied is not valid. Maybe building something like a small low level protocol would help out e.g. 4 bytes raw data length, followed by the raw data itselft, followed by some bytes of checksum (which would allow to verify if the data you have received has been correctly transmitted or not).
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!