我有一个应用程序使用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
;
都编译,但崩溃。在这种情况下,如何让客户端等待服务器?
答案 0 :(得分:4)
永远不要使用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...\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
除非你为库接口编写一个低级资源包装器,否则¹。