sending a large amount of data throught TCP socket

前端 未结 4 1341
广开言路
广开言路 2020-12-21 06:55

This is my first question posted on this forum, and I\'m a beginner in c# world , so this is kind of exciting for me, but I\'m facing some issues with sending a large amount

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-21 07:06

    There are lots of different solutions but chunking is usually a good solution, you can either do this blindly where you keep filling your temporary buffer and then putting it into some stateful buffer until you hit some arbitrary token or the buffer is not completely full, or you can adhere to some sort of contract per tcp message (a message being the overall data to recieve).

    If you were to look at doing some sort of contract then do something like the first N bytes of a message is the descriptor, which you could make as big or as small as you want, but your temp buffer will ONLY read this size up front from the stream.

    A typical header could be something like:

    public struct StreamHeader // 5 bytes
    {
       public byte MessageType {get;set;} // 1 byte
       public int MessageSize {get;set;}  // 4 bytes
    }
    

    So you would read that in then if its small enough allocate the full message size to the temp buffer and read it all in, or if you deem it too big chunk it into sections and keep reading until the total bytes you have received match the MessageSize portion of your header structure.

提交回复
热议问题