【问题标题】:Why doesn't this boost asio code work correctly?为什么这个 boost asio 代码不能正常工作?
【发布时间】:2010-09-20 10:01:00
【问题描述】:

这个 boost udp 服务器没有按预期运行。

它与阻塞的 UDP 回显服务器相同,只是稍作更改。 我正在使用不同的套接字来返回响应,即 sock2。 现在,如果客户端与服务器位于同一台机器上,则此代码可以完美运行。 但是当我在另一台机器上运行它时,没有收到响应。 但是,如果我将发送套接字更改为 sock 而不是 sock2 它确实有效 跨机器。

知道为什么会这样吗? wireshark 根本没有显示任何错误。客户端使用随机源端口,但随后在同一随机端口上调用 recv_from。服务器将响应发送回客户端侦听的同一端口号。

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

using boost::asio::ip::udp;

enum { max_length = 1024 };

void server(boost::asio::io_service& io_service, short port)
{
  udp::socket sock(io_service, udp::endpoint(udp::v4(), port));
  udp::socket sock2(io_service, udp::endpoint(udp::v4(), 0));
  for (;;)
  {
    char data[max_length];
    udp::endpoint sender_endpoint;
    size_t length = sock.receive_from(
        boost::asio::buffer(data, max_length), sender_endpoint);
    printf("Got data, sending response to %s:%d\n", sender_endpoint.address().to_string().c_str(), sender_endpoint.port());
    sock2.send_to(boost::asio::buffer(data, length), sender_endpoint);
  }
}

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

    boost::asio::io_service io_service;

    using namespace std; // For atoi.
    server(io_service, atoi(argv[1]));
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

【问题讨论】:

  • 我在您发布的代码中没有立即看到任何错误。类似于您的last question 使用异步UDP 服务器示例,请发布您的客户端代码。
  • 它是相同的,只是它不能跨网络工作!实际上是从 linux PC 到同一台 PC 上的 windows 虚拟机。但其他代码有效。

标签: boost boost-asio


【解决方案1】:

再次回答我自己的问题!

检查另一台机器上没有运行防火墙软件!。事实证明,VM 中运行的 windows 机器正在运行 windows 防火墙。

我没有立即怀疑这一点,因为当我使用传递给服务器的端口号在原始套接字上发送 UDP 响应时,它起作用了。

我猜windows防火墙正在保持某种状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 2021-01-18
    相关资源
    最近更新 更多