How to deal with multiple part network chuncks of data?

巧了我就是萌 提交于 2021-01-29 18:33:15

问题


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:

  1. 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.

  2. 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.

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!