C 从套接字读取到std :: String

C++ Read From Socket into std::string

本文关键字:std String 读取 套接字      更新时间:2023-10-16

我正在用C 编写一个使用C插座的程序。我需要一个功能来接收我想返回字符串的数据。我知道这将行不通:

std::string Communication::recv(int bytes) {
    std::string output;
    if (read(this->sock, output, bytes)<0) {
        std::cerr << "Failed to read data from socket.n";
    }
    return output;
}

因为 read() *函数为参数带一个char数组指针。在这里返回字符串的最佳方法是什么?我知道我可以从理论上将数据读为char阵列,然后将其转换为字符串,但这对我来说似乎很浪费。有更好的方法吗?

*我实际上并不介意使用其他 read()的东西,如果有一个更合适的替代方案

这是Pastebin上的所有代码,应该在一周内到期。如果我没有答案,那么我将重新调整它:http://pastebin.com/hktdzmst

[update]

我也尝试使用&output[0],但输出包含以下内容:

jello!
[insert a billion bell characters here]

"果冻!"是发送回插座的数据。

这里有一些功能可以帮助您完成所需的功能。它假设您只会从插座的另一端接收ASCII字符。

std::string Communication::recv(int bytes) {
    std::string output(bytes, 0);
    if (read(this->sock, &output[0], bytes-1)<0) {
        std::cerr << "Failed to read data from socket.n";
    }
    return output;
}

std::string Communication::recv(int bytes) {
    std::string output;
    output.resize(bytes);
    int bytes_received = read(this->sock, &output[0], bytes-1);
    if (bytes_received<0) {
        std::cerr << "Failed to read data from socket.n";
        return "";
    }
    output[bytes_received] = 0;
    return output;
}

打印字符串时,请确保使用cout << output.c_str(),因为字符串覆盖operator<<并跳过无法打印的字符,直到达到大小为止。最终,您还可以在功能结束时调整大小,以便接收到的大小,并能够使用普通的cout

正如注释中指出的那样,首先发送大小也是一个好主意,避免字符串类可能不必要的内存分配。