2014-11-08 140 views
0

我使用boost asio來創建客戶端和服務器應用程序。情況是我創建了一個線程來實例化服務器對象,而主線程將實例化客戶端對象。這些對象中的每一個都有自己的io_service,它們在兩個線程中彼此獨立運行。現在我需要的是我想將服務器對象中的某些信息傳回主線程,而不使用客戶端和服務器之間的套接字。我需要傳遞的信息是服務器使用端口(0)獲取的端口以及服務器從客戶端收到的請求。boost asio在兩個線程之間進行通信C++

+1

這是非常很難弄清楚你想要什麼。我抨擊了一些示例代碼。如果沒有回答,請使用它爲您的問題創建SSCCE。 – sehe 2014-11-08 21:20:21

+0

這是一個非常模糊的問題。通常,使用多個'io_service'對象的應用程序可以通過[發佈工作](http://www.boost.org/doc/libs/1_55_0/doc/html/booster_asio/reference/io_service/post.html)相應的io_service。 – 2014-11-10 04:36:31

回答

1

有很多太少代碼,但在這裏有雲:

#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"); 
} 

(這是一個有點胡亂猜測的,因爲你沒有準確地描述在具體條款的問題)

相關問題