boost :: asio :: ip :: tcp :: iostream,首先启动客户端并等待服务器?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了boost :: asio :: ip :: tcp :: iostream,首先启动客户端并等待服务器?相关的知识,希望对你有一定的参考价值。

我有一个应用程序,它使用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* streamError 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)编译但它泄漏了资源,就像没有明天一样。

在这种情况下:

Live On Coliru

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

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

int main() {
    tcp::iostream stream;

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

        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

¹除非您正在为库接口编写低级资源包装器。

以上是关于boost :: asio :: ip :: tcp :: iostream,首先启动客户端并等待服务器?的主要内容,如果未能解决你的问题,请参考以下文章

如何接受boost :: asio :: ssl :: stream 作为boost :: asio :: ip :: tcp :: socket类型的参数

使用 Boost.Asio 获取本地 IP 地址

使用 boost::asio 获取广播源 IP 地址

boost :: asio :: ip :: tcp :: iostream,首先启动客户端并等待服务器?

boost::asio::ip::tcp::iostream,首先启动客户端并等待服务器?

Boost Asio 访问 asio::ip::address 底层数据和字节顺序