【问题标题】:C++ boost.asio server and client connection undersandingC++ boost.asio 服务器和客户端连接undersanding
【发布时间】:2011-11-18 17:41:46
【问题描述】:

我开始学习 boost.asio,但我在理解 tcp 连接方面遇到了一些问题。有来自官方提升网站的例子:

  #include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>

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

std::string make_daytime_string()
{
  using namespace std; // For time_t, time and ctime;
  time_t now = time(0);
  return ctime(&now);
}

int main()
{
  try
  {
    boost::asio::io_service io_service;

    tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13));

    for (;;)
    {
      tcp::socket socket(io_service);
      acceptor.accept(socket);

      std::string message = make_daytime_string();

      boost::system::error_code ignored_error;
      boost::asio::write(socket, boost::asio::buffer(message),
          boost::asio::transfer_all(), ignored_error);
    }
  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

有一个问题,为什么如果我想通过客户端连接到这个服务器我没有写:

    boost::asio::io_service io_service;

tcp::resolver resolver(io_service);
tcp::resolver::query query(host_ip, "daytime"); //why daytime?
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;

为什么是白天?,它是什么意思以及它在服务器中的初始化位置,或者我只是没有错过一些东西?

有完整的客户端代码:www.boost.org/doc/libs/1_39_0/doc/html/boost_asio/tutorial/tutdaytime1.html 感谢您提前解释

【问题讨论】:

    标签: c++ boost tcp boost-asio


    【解决方案1】:

    Daytime 只是另一种协议(如 FTP 等),它使用端口 13。如果您想通过特定端口号连接到服务器,那么您的代码将如下所示:

    tcp::resolver::query query(host_ip, "5678"); // 5678 is the port number
    

    【讨论】:

    • thnx for ansewer,但我可以不使用“白天”这个词,而只使用客户端中的端口数
    • @EdgarBuchvalov 在我的回答中,我向您展示了如何使用特定的端口号。 tcp::resolver::query query(host_ip, "13"); 与使用 "daytime" 相同。
    【解决方案2】:

    daytime是服务名,这在tcp::resolver::querydocumentation中有很好的描述

    服务名称

    标识请求服务的字符串。这可能是描述性的 名称或与端口号对应的数字字符串。可能是一个 空字符串,在这种情况下,所有已解析的端点都有一个端口 0 个数。

    【讨论】:

      【解决方案3】:

      "daytime" 表示用于白天服务的端口。这是您在接受者处看到的13。以下是知名端口的列表(无论是什么意思):

      http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

      【讨论】:

      • ok thnx,此外,是否可以创建自己的端口来连接服务器?还是创建自己的服务器,我可以使用您提供的列表中的每个端口?
      • @Edgar Buchvalov:我不确定你的意思……你可以选择任何你想连接的端口。
      • 不,例如现在我用休闲方式写:tcp::resolver::query query(host_ip, "daytime");我可以写:tcp::resolver::query query(host_ip, 13);会不会一样
      • @Edgar Buchvalov:您应该查看 ASIO 参考,但我认为它必须是 query(host_ip, "13")
      猜你喜欢
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      相关资源
      最近更新 更多