学习提升,并编译了自己的日间服务器客户端 例子. 。由于我无法使用示例中的端口 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;
}
有帮助吗?

解决方案

有几件事将有助于您调试此问题:

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

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

其他提示

什么工作对我来说是改变我创建从端点的方式

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,2008年的MSVC建设)。

我不介意知道为什么会有差别,但至少它的工作原理。

嗯,对1_36增压版本和MSVC 2005 compiller所有的作品。结果 检查你的防火墙设置。

在端口选项接受一个字符串,它可以是该服务的名称,如“白天”,然后它会查找相应端口,或明确的端口,但它必须是一个字符串:

TCP ::的iostream秒(的argv [1], “8087”);

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top