为什么boost :: asio :: read缓冲区数据大小小于读取大小?

时间:2012-03-12 05:30:56

标签: c++ sockets boost-asio

我有一个简单的文件传输应用程序,它从客户端每次传输传输4096个字节。在服务器端,我使用以下调用read

tempLen = boost :: asio :: read(l_Socket,boost :: asio :: buffer(buf,bufSize),boost :: asio :: transfer_all(),error);

templen是1440字节,但是当我读取buf时,它只有11个字节。复制粘贴下面的服务器代码。我已经尝试过socket.read_some和asio :: read - 两者都以相同的结果结束。有人可以解释我在这里做错了什么吗?

//boost::array<char, 4096> buf;
char* buf = new char[4096];
char* bigBuffer = new char[2097152];
std::string strBuffer;

strBuffer.clear();

for (;;) // Loop for the whole file length
{

    boost::asio::read_until(l_Socket, request_buf, "\n\n");
    std::istream request_stream(&request_buf);
    request_stream >> bufSize;
    std::cout<< "Size of the Compressed data transfer:" << bufSize << "\n";

    // Clear the stream
    request_stream.clear();
    memset(bigBuffer, 0, 2097152);
    memset(buf, 0, 4096);

    if(bufSize == 0)
        break;

    size_t len = 0, prevLen = 0, tempLen = 0;

    try{

        //tempLen = l_Socket.read_some(boost::asio::buffer(buf, bufSize), error);
        tempLen = boost::asio::read(l_Socket, boost::asio::buffer(buf, bufSize), boost::asio::transfer_all(), error);
        std::cout << "Length from read: " << tempLen << " Buffer Size: " << bufSize << std::endl;
        prevLen = len;

        len += tempLen;

    }
    catch (boost::exception& e)
    {
         std::cerr << diagnostic_information(e);
    }.....}

编辑:

只是在我在客户端发送使用以下函数压缩的数据时才检查此问题。

    std::string CClient::Compress(const char* data, unsigned int* dataLen)
{
    std::stringstream compressed;
    std::stringstream decompressed;
    std::cout << "From Compress Function: " << " Size of Decompressed Data: " << strlen(data) << std::endl;
    decompressed << data;
    boost::iostreams::filtering_streambuf<boost::iostreams::input> out;
    out.push(boost::iostreams::zlib_compressor());
    out.push(decompressed);
    boost::iostreams::copy(out, compressed);
    *dataLen = compressed.str().size();
    return compressed.str();
}

std::string CClient::DeCompress(const std::string& data)
{
    std::stringstream compressed;
    std::stringstream decompressed;
    compressed << data;
    boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
    in.push(boost::iostreams::zlib_decompressor());
    in.push(compressed);
    boost::iostreams::copy(in, decompressed);
    std::cout << "Decompressed Data: " << decompressed.str().c_str() << std::endl;
    return decompressed.str();
}

当我在压缩之后(发送之前)解压缩“客户端”本身的数据时,数据将被正确打印。但是当我在服务器上收到数据后,我正面临着这个问题。

1 个答案:

答案 0 :(得分:1)

问题似乎在于压缩功能。从Compression函数返回的字符串,当我将其转换为c字符串时,它终止11个字节。我通过实现压缩函数直接调用zlib函数并将数据作为char字符串而不是std :: string来解决问题。