boost官方文件中聊天程式連續發包崩潰問題
阿新 • • 發佈:2019-02-01
- void do_write(chat_message msg)
- {
- bool write_in_progress = !write_msgs_.empty(); //空的話變數為false
- write_msgs_.push_back(msg); //把要寫的資料push至寫佇列
- if (!write_in_progress)//佇列初始為空 push一個msg後就有一個元素了
- {
- boost::asio::async_write(socket_,
-
boost::asio::buffer(write_msgs_.front().data(),
- write_msgs_.front().length()),
- boost::bind(&chat_client::handle_write, this,
- boost::asio::placeholders::error));
- }
- }
- void handle_write(const boost::system::error_code& error)//第一個訊息單獨處理,剩下的才更好操作
- {
- if (!error)
- {
-
write_msgs_.pop_front();//剛才處理完一個數據 所以要pop一個
- if (!write_msgs_.empty())
- {
- boost::asio::async_write(socket_,
- boost::asio::buffer(write_msgs_.front().data(),
- write_msgs_.front().length()),
- boost::bind(&chat_client::handle_write, this,
-
boost::asio::placeholders::error)); //迴圈處理剩餘的訊息
- }
- }
{
boost::mutex::scoped_lock lock(mtx);
if (msg.data() !=NULL )
write_msgs_.push_back(msg); //把要寫的資料push至寫佇列
if (!write_msgs_.empty())//佇列初始為空 push一個msg後就有一個元素了
{
Message_Base Info = write_msgs_.front();
boost::asio::async_write(socket_,
boost::asio::buffer(Info.data(),
Info.length()),
boost::bind(&chat_client::handle_write, this,
boost::asio::placeholders::error));
}
}
void handle_write(const boost::system::error_code& error)//第一個訊息單獨處理,剩下的才更好操作
{
boost::mutex::scoped_lock lock(mtx);
if (!error)
{
if (!write_msgs_.empty())
write_msgs_.pop_front();//剛才處理完一個數據 所以要pop一個
if (!write_msgs_.empty())
{
Message_Base Info = write_msgs_.front();
boost::asio::async_write(socket_,
boost::asio::buffer(Info.data(),
Info.length()),
boost::bind(&chat_client::handle_write, this,
boost::asio::placeholders::error)); //迴圈處理剩餘的訊息
}
}
else
{
if (m_pCallBackTimeOut)
m_pCallBackTimeOut(RESULT_ERROR, (char*)error.message().c_str());
do_close();
}
}