【问题标题】:Simple server/client boost example not working简单的服务器/客户端增强示例不起作用
【发布时间】:2009-04-04 19:11:53
【问题描述】:

学习提升,编译了他们的日间服务器客户端example。由于我不能使用示例中的端口 13,我只更改了服务器和客户端示例中的端口号。服务器运行正常,但是客户端好像连接不上,没有报错。

客户端的输入数据是“127.0.0.1”。

服务器:

#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::endpoint endpoint(tcp::v4(), 8087);
    tcp::acceptor acceptor(io_service, endpoint);

    for (;;)
    {
      tcp::iostream stream;
      acceptor.accept(*stream.rdbuf());
      stream << "test" << make_daytime_string();
    }
  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

还有客户:

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

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

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 2)
    {
      std::cerr << "Usage: daytime_client <host>" << std::endl;
      return 1;
    }

    tcp::iostream s(argv[1], 8087);
    std::string line;
    std::getline(s, line);
    std::cout << line << std::endl;
  }
  catch (std::exception& e)
  {
    std::cout << "Exception: " << e.what() << std::endl;
  }

  return 0;
}

【问题讨论】:

  • 你试过独立于服务器的客户端吗?

标签: c++ boost tcp boost-iostreams


【解决方案1】:

对我有用的是改变我创建端点的方式

tcp::endpoint( tcp::v4(), port );

tcp::endpoint( boost::asio::ip::address::from_string("127.0.0.1"), port );

第一种方法创建 0.0.0.0 的端点,该端点在 Mac OS X 上运行良好,但在 Windows(XP,使用 MSVC 2008 构建)上显示“无效”消息。

我不介意知道为什么会有差异,但至少它有效。

【讨论】:

    【解决方案2】:

    一些事情将有助于为您调试:

    1. 你在运行什么平台
    2. 您使用的是什么编译器,包括版本
    3. 您使用的是什么版本的 boost

    另外,要检查的一件事是服务器是否绑定到 127.0.0.1 或外部接口。尝试使用外部接口的 IP 地址而不是 127.0.0.1。在 windows 中使用 ipconfig 进行检查,在 linux 中使用 ifconfig 进行检查。

    【讨论】:

      【解决方案3】:

      嗯,所有工作都在 1_36 boost 版本和 msvc 2005 编译器上运行。
      检查您的防火墙设置。

      【讨论】:

        【解决方案4】:

        port选项接受一个字符串,可以是服务的名称,为“daytime”,然后会查找对应的端口,或者显式的端口,但必须是字符串:

        tcp::iostream s(argv[1], "8087");

        【讨论】:

          猜你喜欢
          • 2011-09-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-08
          相关资源
          最近更新 更多