Boost asio - separate different chunks of data

孤人 提交于 2020-01-11 12:25:51

问题


Imagine we create simple client-server app to send files from client to server. We use boost asio.

Server starts listening. Client connects to the server. Client send filename and file content.

But server receive just a stream of bytes. How server detect end of filename and start of file content?

First idea I have is to use special delimiter. Client writes into the socket filename, then delimiter, then file content. Server uses 'read_until' to receive filename and 'read' to read file content.

Is it a good solution?

What if I want to sent 10 files in a row - searching for delimiter in the byte stream may be expensive...


回答1:


First idea I have is to use special delimiter.

That's the right way. It's the responsibility of your protocol. And the protocol may define length headers, or special delimiters.

Length headers are more common in binary protocols (BSON-like).

Special delimiters are common in text protocols.

Client writes into the socket filename, then delimiter, then file content.

Server uses 'read_until' to receive filename and 'read' to read file content.

Is it a good solution?

Yes. As long as you remember that read_until reads until a packet is received that contains the delimiter. I may read more, so you might already have (part) of the content at the same time.

See also: Missing the first characters using boost::asio::streambuf



来源:https://stackoverflow.com/questions/33845876/boost-asio-separate-different-chunks-of-data

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