Eugene Eugene - 9 days ago 5x
C++ Question

c++ asio socket read answer from server

I got simple server-client app.

The idia is:
Client send to server string with sql-request.
Server process the request and send back on client answer with data formated in csv style string.

Everything is already adjusted accept one thing. The problem is to read answer on client cause I don't know the size of recieved string.

Code is bellow:


std::string answer;
answer = sql_read(*msg); //get the string with data from request
clientSock->write_some(buffer(answer, answer.size())); //send it back on client


std::string answer;
bytesRead = sock->read_some(boost::asio::buffer(readBuf, inputSize)); //read the answer, but how do I know correct size of string?
string_ptr msg(new std::string(readBuf, bytesRead));
answer = *msg;

How to read the resulting string without knowing its size?
Or if my aproach (with sending data in string) is radically wrong how to do it in correct way?


You must handle this yourself in the protocol the client and server use to speak to each other.

One way is to use a deliminator and use boost::asio::read_until(). Example:

boost::asio::streambuf buf;
boost::asio::read_until (sock, buf, "\r\n");  // or '\0' if zero terminated

Check the Boost.Asio documentation

Another way is to send the size in an fixed length header before sending the variable length part.