Boost Tcp客户端收到崩溃

时间:2017-06-07 05:16:58

标签: c++ boost tcp boost-asio boost-thread

我最近一直在使用Windows Visual Studio 2015的Boost库。我最近一直致力于通过tcp连接轻松传输数据的服务器和客户端。但最近我试图向客户端发送一个Base64编码的文件字符串,大约是366,660字节的数据。为此,我将数据拆分为大小约为1000的数据包。 (不确定最大大小是多少)但是无论如何服务器完全正确地发送数据但是当客户端收到超过160,000个字节时它会崩溃,没有例外。

客户端:

try
{
    for (static int i = 1000; i <= sizeofpackets /*(366,660) (currently 170,000 for testing)*/; i += 1000)
    {
        char Buffer[1000];
        memset(Buffer, 0, 1000);
        boost::asio::read(s, boost::asio::buffer(Buffer, 1000));
        std::cout << i << std::endl;
    }
}
catch (std::exception& e)
{
    std::cerr << "Exception: " << e.what() << "\n";
}

服务器:

for (int i = 1000; i <= 170000; i += 1000)
{
    std::string NewData = encodedBuffer.substr(i - 1000, i);
    NewData.erase(0, i - 1000);
    boost::asio::write(*sock, boost::asio::buffer(NewData, 1000));
    std::cout << NewData.size() + i - 1000 << std::endl;
    NewData.clear();
}

任何评论或建议都会有所帮助!

1 个答案:

答案 0 :(得分:0)

你还没有发布完整的代码,所以很难说,但你的问题可能是你处理字符串的方式,而不是你处理套接字传输的方式(substr()成员函数需要一个开始偏移量和大小,看起来你正试图使用​​不断增加的NewData大小。)

以下(完整)代码,它使用您的客户端和服务器代码作为参考,但字符串处理已更改,确实在我的机器上传输170000字节,因此它可能会有所帮助:

#include <boost/asio/io_service.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <array>
#include <string>
#include <iostream>


namespace
{
    const size_t BIG_MESSAGE_SIZE = 170000;
    const size_t BLOCK_SIZE = 1000;

    void doTX(boost::asio::ip::tcp::socket& socket, size_t& TXsize)
    {
        char rawBuffer[BIG_MESSAGE_SIZE] = { 0 }; // raw data to send
        std::string encodedBuffer(rawBuffer, BIG_MESSAGE_SIZE);
        for (size_t i = 0; i < BIG_MESSAGE_SIZE; i += BLOCK_SIZE)
        {
            std::string NewData = encodedBuffer.substr(i, BLOCK_SIZE);
            TXsize += boost::asio::write(socket, boost::asio::buffer(NewData, BLOCK_SIZE));
        }
    }

    void doRX(boost::asio::ip::tcp::socket& socket, size_t& RXsize)
    {
        for (size_t i = 0; i < BIG_MESSAGE_SIZE; i += BLOCK_SIZE)
        {
            char Buffer[BLOCK_SIZE];
            memset(Buffer, 0, BLOCK_SIZE);
            RXsize += boost::asio::read(socket, boost::asio::buffer(Buffer, BLOCK_SIZE));
        }
    }
}

int main(int argc, char * argv[])
{
    std::cout << "Running:" << std::endl;

    int port = 9876;

    boost::asio::io_service ios;
    boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), port);
    boost::asio::ip::tcp::acceptor acceptor(ios, endpoint);
    boost::asio::ip::tcp::socket TXsocket(ios);
    boost::asio::ip::tcp::socket RXsocket(ios);

    TXsocket.connect(endpoint);
    acceptor.accept(RXsocket);

    size_t TXsize = 0;
    size_t RXsize = 0;

    doTX(TXsocket, TXsize);
    doRX(RXsocket, RXsize);

    std::cout << TXsize << " " << RXsize << std::endl;

    return 0;
}