【问题标题】:How to print out to standard output a boost::asio::ip::tcp::v4如何将 boost::asio::ip::tcp::v4 打印到标准输出
【发布时间】:2020-09-12 18:09:36
【问题描述】:

我正在运行 boost.asio 示例中的 c++11 聊天示例,并尝试打印出 tcp::v4() 返回值以查看服务器使用的 IP 地址。没有 to_string 函数可以在 boost::asio::ip::tcp 上工作,就像在 boost::asio::ip 上一样。

以下是聊天示例的 server.cpp 中的主要功能:

int main(int argc, char* argv[])
{
  try
  {
    if (argc < 2)
    {
      std::cerr << "Usage: chat_server <port> [<port> ...]\n";
      return 1;
    }

    boost::asio::io_context io_context;

    std::list<chat_server> servers;

    for (int i = 1; i < argc; ++i)
    {
      tcp::endpoint endpoint(tcp::v4(), std::atoi(argv[i]));
      servers.emplace_back(io_context, endpoint);
    }

    io_context.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

【问题讨论】:

    标签: c++ tcp boost-asio ipv4


    【解决方案1】:

    在 boost::asio::ip::tcp 上没有 to_string 函数,就像在 boost::asio::ip 上一样

    这很困惑。 boost::asio::ip::tcp 是一个你永远不会实例化的类(它是一个对协议建模的静态类),boost::asio::ip 是一个命名空间,你不能期望打印一个命名空间。

    然后,您的示例中有很多不相关的代码。为此,我们假设您的 chat_server 是试图打印端点的那个:

    Live On Coliru

    struct chat_server {
        chat_server(boost::asio::io_context&, tcp::endpoint ep) {
            std::cout << "Serving on " << ep << "\n";
        }
    };
    

    打印类似的东西

    Serving on 0.0.0.0:100
    Serving on 0.0.0.0:110
    Serving on 0.0.0.0:120
    ...
    

    如果你真的想用问题标题文字,你会打印端点的地址部分:

        std::cout << "Serving on " << ep.address() << "\n";
    

    打印出稍微没用的

    Serving on 0.0.0.0
    Serving on 0.0.0.0
    Serving on 0.0.0.0
    ...
    

    那是因为您没有绑定到接口。如果你这样做会更有用:

    Live On Coliru

            tcp::endpoint endpoint(ip::address_v4::loopback(), std::atoi(argv[i]));
    
    Serving on 127.0.0.1
    Serving on 127.0.0.1
    Serving on 127.0.0.1
    

    TL;DR

    你需要的所有代码:

    #include <boost/asio.hpp>
    #include <iostream>
    
    int main() {
        std::cout << boost::asio::ip::address_v4::loopback() << "\n";
    }
    

    【讨论】:

    • 我的问题确实很困惑,但你为我阐明了这一点。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-06-08
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    相关资源
    最近更新 更多