问题
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