提问者:小点点

我无法用网络TS重写Boost::ASIO教程。我的代码怎么了?


我尝试制作本教程的网络TS版本:https://www.boost.org/doc/libs/1_75_0/doc/html/boost_asio/tutorial/tutdaytime2/src.html

首先,我编译并运行了boost版本,它运行得很好。

然后我写了这样的话:

#include <ctime>
#include <iostream>
#include <string>

#include <experimental/net>
namespace net = std::experimental::net;

/////////////////////////////////////////////////////////////////////////////
std::string make_daytime_string()
/////////////////////////////////////////////////////////////////////////////
{
 time_t now = std::time(0);
 const std::string result = std::ctime(&now);
 std::cout << "sending: " << result << '\n';
 return result;
}

/////////////////////////////////////////////////////////////////////////////
int main()
/////////////////////////////////////////////////////////////////////////////
{
 try
 {
  net::io_context io_context;

  net::ip::tcp::acceptor acceptor
  (
   io_context,
   net::ip::tcp::endpoint(net::ip::tcp::v4(), 8013)
  );

  while (true)
  {
   net::ip::tcp::socket socket(io_context);
   acceptor.accept(io_context);
   net::write(socket, net::buffer(make_daytime_string()));
  }
 }
 catch (std::exception& e)
 {
  std::cerr << e.what() << std::endl;
 }

 return 0;
}

我正在使用网络ts的实现:https://github.com/chriskohlhoff/networking-ts-impl

我正在Ubuntu20.04LTS中使用gcc进行编译。

服务器代码编译并运行。但一旦客户端建立连接,它就会失败,但有以下例外情况:

write: Bad file descriptor

,而客户端没有收到任何东西。我的代码看起来真的和asio的一样。为什么会失败?


共1个答案

匿名用户

   net::ip::tcp::socket socket(io_context);
   acceptor.accept(io_context);

您将丢弃连接的套接字(并从已经传递给accept的执行上下文中冗余地构造一个套接字)。

用修复

    auto socket = acceptor.accept(io_context);