[英]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)
编译,但是它泄漏资源,就像没有明天一样。
在这种情况下:
#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.