Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
876 views
in Technique[技术] by (71.8m points)

c++ - Sending and receiving std::string over socket

I have seen similar question on SO but non answers my question. Here I am trying to send and recv string:

I am sending std::string :

if( (bytecount=send(hsock, input_string.c_str(), input_string.length(),0))== -1)

Can it be correctly received by this?

if ((bytecount = recv(*csock, rcv.c_str(), rcv.length(), 0)) == -1)

I am getting error:

error: invalid conversion from ‘const void*’ to ‘void*’ [-fpermissive]` on recv line!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...