No it can't. c_str() returns a const char*
. This means you cannot overwrite the contents of the pointer.
If you want to receive the data, you must create a buffer, e.g. with a std::vector
and then use that to create a std::string
.
// create the buffer with space for the data
const unsigned int MAX_BUF_LENGTH = 4096;
std::vector<char> buffer(MAX_BUF_LENGTH);
std::string rcv;
int bytesReceived = 0;
do {
bytesReceived = recv(*csock, &buffer[0], buffer.size(), 0);
// append string from buffer.
if ( bytesReceived == -1 ) {
// error
} else {
rcv.append( buffer.cbegin(), buffer.cend() );
}
} while ( bytesReceived == MAX_BUF_LENGTH );
// At this point we have the available data (which may not be a complete
// application level message).
The above code will receive 4096 bytes at a time. If there is more than 4K sent, it will keep looping and append the data to recv
until there is no more data.
Also note the use of &buffer[0]
instead of buffer.data()
. Taking the address of the first element is the way to access the non-const pointer and avoid undefined behavior.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…