问题
I'm writing a network client for a given protocol using TCP and I'm having having some philosophical issues with the overall architecture of the thing. Sometimes it may happen that I don't have the whole request data and I may need to read a few more bytes than what's available at the moment, and I imagine sometimes I can get parts of another request after the one I want. What's the usual approach in this kind of situations?
回答1:
TCP sockets are Stream-Oriented. That means that reading them is the same as reading a file. If you want to pass discrete messages over TCP, you'll need to split the stream of data into messages, just like the new line character splits text files into lines. This is called framing.
There many ways of doing this, here are some examples:
A counting approach - each message is prefixed by its length. say "5apple". You read the "5" first, then you know how many bytes are in this message, and that the 6th byte will be the first byte of the next message. You might need several length bytes if some of your messages are long.
A delimiter approach - have a special character (say null) signal the end of one message and the start of the next one. Then just read from the socket until you reach this delimiter. Note however that you have to make sure that this character will never appear WITHIN your messages since that will screw everything up.
Fixed size messages - similar to the first approach, only with the length field being implicit. Make sure that all of your messages are have a fixed length (use padding if needed), then just read the correct number of bytes from the socket each time.
来源:https://stackoverflow.com/questions/27566158/how-to-deal-with-multiple-part-network-chuncks-of-data