How can I Receive a Large Data Stream through a Socket Connection - without TCPClient

后端 未结 1 1594
太阳男子
太阳男子 2021-01-25 23:13

I have the Problem, that I want to send a large string through a SocketConnection, but I can\'t receive the string at once because the Network is limited to 1500 bytes, so how c

相关标签:
1条回答
  • 2021-01-25 23:46

    TCP is a byte stream, it has no concept of messages. The size of the individual packets on the wire is irrelevant, it is just an implementation detail of the networking hardware. TCP guarantees that what you send is what you receive (but there is no 1-to-1 relationship between the size of individual sends and the size of individual reads, like there is in UDP).

    The solution requires the sender to frame the string data in such a way that allows the reader to know when to stop reading. Either:

    1. send the string length before sending the string data. The reader can then read the length first and then read the specified number of following bytes.

    2. a. terminate the string with a unique delimiter that cannot appear in the string itself. The reader can then keep reading until it encounters the delimiter.

      b. the delimiter can be closure of the connection. The reader can keep reading until a disconnect is detected.

    Which solution you need to use depends on the particular protocol you are implementing. #1 is best for binary protocols, and allows for efficient memory managent, whereas #2 is more suited to text-based protocols, or streaming protocols where the final length is not know ahead of time. Sometimes protocols have to resort to #2b (HTTP and FTP both utilize it as times) when #1 and #2a are not possible.

    0 讨论(0)
提交回复
热议问题