簡體   English   中英

boost :: asio :: ip :: tcp :: iostream,首先啟動客戶端並等待服務器?

[英]boost::asio::ip::tcp::iostream, launch client first and wait for server?

我有一個使用boost :: asio :: ip :: tcp :: iostream通過TCP連接到另一個應用程序的應用程序。

我的服務器代碼是:

static auto const flags = boost::archive::no_header | boost::archive::no_tracking;
boost::asio::io_service ios;
boost::asio::ip::tcp::endpoint endpoint
= boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 4444);
boost::asio::ip::tcp::acceptor acceptor(ios, endpoint);
boost::asio::ip::tcp::iostream stream;

//program stops here until client connects.
acceptor.accept(*stream.rdbuf());

我的客戶是:

std::string ip = "127.0.0.1";

    boost::asio::ip::tcp::iostream stream(ip, "4444");

    if (!stream)
        throw std::runtime_error("can't connect");

如果首先啟動服務器,則效果很好。 但是,如果首先啟動客戶端,它將拋出錯誤並崩潰。 我想做的是能夠首先啟動任一端,並讓它等待連接。 客戶顯然是問題所在,所以我正在嘗試:

 bool bConnected;

    std::string ip = "127.0.0.1";
    boost::asio::ip::tcp::iostream* stream;

    while (!bConnected)
    {
        stream = new boost::asio::ip::tcp::iostream(ip, "4444");
        if (!stream)
        {
            std::cout << "cannot find datastream" << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
            //throw std::runtime_error("can't connect");
        }

        if (stream)
        {
            bConnected = true;
        }

    }

這不會編譯,在boost::asio::ip::tcp::iostream* stream上給我一個錯誤, Error C4703 potentially uninitialized local pointer variable 'stream' used 我努力了:

boost::asio::ip::tcp::iostream* stream = nullptr; boost::asio::ip::tcp::iostream* stream = NULL ;

兩者都可以編譯,但是會崩潰。 在這種情況下,如何讓客戶端等待服務器?

切勿使用new ¹。 因為正如您所評論的那樣, if (!*stream) 編譯,但是它泄漏資源,就像沒有明天一樣。

在這種情況下:

生活在Coliru

#include <boost/asio.hpp>
#include <iostream>
#include <thread>

using boost::asio::ip::tcp;

int main() {
    tcp::iostream stream;

    do {
        std::cout << "Connecting...\n";

        stream.clear();
        stream.connect("127.0.0.1", "4444");

        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    } while (!stream);

    std::cout << "Connected! " << stream.rdbuf();
}

哪些打印:

Connecting...
Connecting...
Connecting...
Connecting...
Connecting...
Connecting...
Connected! Hello world

¹除非您正在為庫接口編寫低級資源包裝器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM