下面的代碼肯定能行,但並不快如我所料。read_some()的作品,但速度很慢,閱讀()不
我希望我的程序在很好的速度讀取數據。還有另一個商業應用程序連接到相同的服務器&以驚人的速度獲取數據。服務器端不是問題。
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()調用不會返回。
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()。
更換你可能要考慮重新設計程序中使用異步函數來代替。每個異步讀取回調都會收到一部分消息,當收到完整的消息時,將其放入隊列中並讓主線程處理它。 – 2014-12-03 09:08:19
不是因爲你的線程睡了10ms'boost :: this_thread :: sleep(boost :: posix_time :: milliseconds(10));'? – doc 2014-12-03 09:09:25
@doc,不!!!!!!! – user1 2014-12-03 09:11:48