c++ - 简单的服务器/客户端 boost 示例不起作用

标签 c++ boost tcp boost-iostreams

学习 boost ,编译了自己的白天服务器客户端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;
}

最佳答案

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

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 构建)上给出“无效”消息。

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

关于c++ - 简单的服务器/客户端 boost 示例不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/717618/

相关文章:

c++ - 计算一个点号的校验和

Cuda 生成的 VC++ 解决方案上的 Boost 错误(错误 C2675)

C# - 套接字未接收所有字节

c++ - 错误 : undefined reference to `MainWindow::on_Input_A_textChanged(QString const&)'

C++ STL Vector of lists 在列表末尾插入元素

c++ - 我如何在 C++11 中实现类似 "interrupted exception"行为的 Java

c++ - 使用 boost::spirit 解析 Newick 语法

c++ - 如何确定 boost::any 是否包含文字字符串?

javascript - Modbus TCP 到 JavaScript 的转换

tcp - Ethereal 转储中的 TSV 和 TSER 字段是什么意思?