我正在使用 boost asio 创建客户端和服务器应用程序。情况是我创建了一个线程来实例化服务器对象,而主线程将实例化客户端对象。这些对象中的每一个都有自己的 io_service,它们在两个线程中彼此独立运行。我现在需要的是我想在不使用客户端和服务器之间的套接字的情况下将一些信息从服务器对象传回主线程。我需要传递的信息是服务器使用端口(0)获取的端口和服务器从客户端收到的请求。
最佳答案
有很多太少的代码,但这里是:
#include <boost/asio.hpp>
#include <boost/optional.hpp>
#include <boost/thread.hpp>
#include <iostream>
using namespace boost::asio;
struct asio_object {
protected:
mutable io_service io_service_;
private:
boost::optional<io_service::work> work_ { io_service::work(io_service_) };
boost::thread th { [&]{ io_service_.run(); } };
protected:
asio_object() = default;
~asio_object() { work_.reset(); th.join(); }
};
struct Client : asio_object {
public:
void set_message(std::string data) {
io_service_.post([=]{
message = data;
std::cout << "Debug: message has been set to '" << message << "'\n";
});
}
private:
std::string message;
};
struct Server : asio_object {
Client& client_;
Server(Client& client) : client_(client) {}
void tell_client(std::string message) const {
client_.set_message(message);
}
};
int main()
{
Client client;
Server server(client);
server.tell_client("Hello world");
}
(这是一个有点疯狂的猜测,因为你没有用准确的术语准确描述你的问题)
关于c++ - boost asio在两个线程c++之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26817250/