gpt4 book ai didi

c++ - read_some() 工作但很慢, read() 没有

转载 作者:行者123 更新时间:2023-11-28 02:36:27 24 4
gpt4 key购买 nike

下面的代码绝对有效,但速度不如我预期。

我希望我的程序能够以非常快的速度读取数据。还有另一个商业应用程序连接到同一台服务器并以惊人的速度检索数据。服务器端不是问题。

class A
{
//...

boost::asio::ip::tcp::socket* myPort;
}

void A::OpenPort()
{
if(myPort)
{
if(myPort->is_open())
{
return;
}
}

// make the connection
Connect();

if(! myPort->is_open())
{
return;
}

// set the protocol
static string init("INIT\r\n");
myPort->write_some(boost::asio::buffer(init.c_str(), init.length()));
}

void A::Read()
{
static string prev_msg = "";

try
{
OpenPort();

while(true)
{
boost::system::error_code error;

boost::asio::streambuf streamBuf;
boost::asio::streambuf::mutable_buffers_type mutableBuffer = streamBuf.prepare(614400);
size_t bytes_transferred = myPort->read_some(boost::asio::buffer(mutableBuffer), error);

if (error)
{
if (error != boost::asio::error::eof)
{
throw boost::system::system_error(error); // Some other error.
}
}

// add to any previous message we might not have processed
streamBuf.commit(bytes_transferred);
istreambuf_iterator<char> sbit(&streamBuf);
istreambuf_iterator<char> end;
string s(sbit, end);
prev_msg.append(s);

string delimiter1 = ",\r\n";

size_t pos1 = 0;

string response;

while ((pos1 = prev_msg.find(delimiter1)) != std::string::npos)
{
response = prev_msg.substr(0, pos1);

//SOME PROCESSING ON THE RESPONSE RECEIVED
}
}
}
catch (boost::system::system_error const& ex)
{
cout<<ex.what();
}
}

很明显,问题出在read_some(),程序在一次读取操作中没有读取完整的数据,有时会收到614000字节,有时会很少。我不想对缓冲区的大小施加任何限制,无论服务器发送什么,程序都应该一次性读取所有数据。

因此,我决定只使用 read()。但是,现在程序卡在了 read(); read() 调用不返回。

boost::asio::streambuf streamBuf;
size_t bytes_transferred = read(*myPort, streamBuf, error);

if (error)
{
if (error != boost::asio::error::eof)
{
throw boost::system::system_error(error); // Some other error.
}
}

我必须在请求下一个数据之前处理接收到的数据,因此我不能使用 async_read()。

最佳答案

不要在每个循环中都分配一个新的缓冲区,只在循环外分配一次。

    while(true)
{
boost::system::error_code error;

boost::asio::streambuf streamBuf;
boost::asio::streambuf::mutable_buffers_type mutableBuffer = streamBuf.prepare(614400);
size_t bytes_transferred = myPort->read_some(boost::asio::buffer(mutableBuffer), error);
...

被替换为

    boost::system::error_code error;
boost::asio::streambuf streamBuf;
boost::asio::streambuf::mutable_buffers_type mutableBuffer = streamBuf.prepare(614400);
while(true)
{
size_t bytes_transferred = myPort->read_some(boost::asio::buffer(mutableBuffer), error);
...

关于c++ - read_some() 工作但很慢, read() 没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27267483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com