且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过套接字发送和接收std :: string

更新时间:2021-11-27 08:11:00

不行。 c_str()返回 const char *

如果要接收数据,则必须创建一个缓冲区,例如:带有 std :: vector ,然后使用它来创建 std :: string

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). 

以上代码将一次接收4096个字节。如果发送的数据超过4K,它将继续循环并将数据附加到 recv ,直到没有更多数据为止。

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.

还请注意,使用& buffer [0] 代替 buffer.data ()。获取第一个元素的地址是访问非const指针并避免未定义行为的方法。

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.