gpt4 book ai didi

c++ - Boost 客户端卡住

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

http://www.boost.org/doc/libs/1_46_0/doc/html/boost_asio/example/chat/chat_client.cpp

我正在根据上面的示例开发客户端应用程序。

我想在单独的线程中进行客户端连接,这样 UI 就不会卡住。这里 UI 卡住了。
1. 你能告诉我如何实现吗?
2.这一行是什么意思? boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));
t.join();
此行是否为连接创建了单独的线程?

 client::client(boost::asio::io_service& io_service, tcp::resolver::iterator endpoint_iterator)
: io_service_(io_service),
resolver_(io_service),
socket_(io_service_)
{
tcp::endpoint endpoint = *endpoint_iterator;
socket_.async_connect( endpoint,
boost::bind(&client::handle_connect, this,boost::asio::placeholders::error,
++endpoint_iterator));

}
void client::handle_connect(const boost::system::error_code& error,
tcp::resolver::iterator endpoint_iterator)
{
strcpy(data_,"Hello");
if (!error)
{
/*boost::asio::async_read(socket_,
boost::asio::buffer(data_, MAX_PATH),
boost::bind(&client::handle_read, this,
boost::asio::placeholders::error));*/
boost::asio::async_write(socket_, boost::asio::buffer(data_, MAX_PATH),
boost::bind(&client::handle_read, this,
boost::asio::placeholders::error));
}
else if (endpoint_iterator != tcp::resolver::iterator())
{
socket_.close();
tcp::endpoint endpoint = *endpoint_iterator;
socket_.async_connect( endpoint,
boost::bind(&client::handle_connect, this,
boost::asio::placeholders::error, ++endpoint_iterator));
}
}

void client::handle_read(const boost::system::error_code& error)
{
if (!error)
{
memset(data_,0,MAX_PATH);
boost::asio::async_read( socket_,
boost::asio::buffer(data_, MAX_PATH),
boost::bind(&client::handle_read, this,
boost::asio::placeholders::error));

if (strcmp(data_,"Hello Response")==0)
{
MessageBox(NULL,_T("Regd Done"),_T("Vue"),1);
// return ;
}


}

}

CConnectionMgr::CConnectionMgr(void)
{

}
void CConnectionMgr::Connect()
{
try
{
char* host = "192.168.4.84";
char* port = "55555";
boost::asio::io_service io_service;

tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(),host , port);
tcp::resolver::iterator iterator = resolver.resolve(query);

c = new client(io_service, iterator);

//boost::thread thrd(boost::bind(&boost::asio::io_service::run, &io_service));
boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));
t.join();
// MessageBox(NULL,_T("Join"),_T("ff"),1);
}
catch (std::exception& e)
{
CString csMsg(e.what());
MessageBox(NULL,csMsg,_T("ff"),1);
}
}

最佳答案

“t.join()”等待线程“t”退出。线程 't' 正在 io_service 上运行 run() 方法,当没有剩余的 I/O 需要完成时将退出。

因此,您的 Connect() 方法将阻塞,直到所有 I/O 完成,这显然不是您想要的。如果您打算执行异步 I/O 以便您的客户端不会阻塞,您需要为您的 I/O 上下文设计一种方式来与我们的 UI 上下文进行通信。这不会靠魔法发生。

关于c++ - Boost 客户端卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5482203/

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