recv() 获取损坏的数据

recv() gets corrupted data

本文关键字:数据 损坏 获取 recv      更新时间:2023-10-16

我正在尝试从C++应用程序中的C#服务器接收大数据(约7MB)。我使用此库来执行此操作:https://github.com/DFHack/clsocket但是当我收到它时,我得到严重损坏的数据。这是我如何获得它的代码:

unsigned char* image_data = client->ReadBytes(lmi_reply);

lmi_reply是我想要接收的确切数据大小。 ReadBytes

uint8* Client::ReadBytes(int r) {
    try {
        uint8* data = new uint8(r);
        this->m_s->Receive(r, data); // m_s is the CActiveSocket object.
        return data;
    }
    catch (...) {
        return 0;
    }
}

我做错了什么?

附言当我同时使用 C# 客户端和服务器时,数据与服务器上的数据完全相同。

我通过将我的 ReadBytes 更改为以下内容来解决此问题:

uint8* Client::ReadBytes(int r) {
    try {
        char* data = new char[r];
        memset(data, 0, r);
        int maxBufferSize = 8192;
        auto bytesReceived = decltype(r){0};
        while (r > 0)
        {
            const auto bytesRequested = (r > maxBufferSize) ? maxBufferSize : r;
            const auto returnValue = recv(this->m_s->GetSocketDescriptor(), data + bytesReceived, bytesRequested, 0);
            if (returnValue == -1 || returnValue == 0)
                return (uint8*)data;
            bytesReceived += returnValue;
            r -= returnValue;
        }
        return (uint8*)data;
    }
    catch (...) {
        return 0;
    }
}