我未能使用网络 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

我在Ubuntu 20.04 LTS中使用gcc进行编译。

服务器代码编译并运行。但一旦客户端建立连接,它就会失败,出现以下异常:

write: Bad file descriptor

,并且客户端没有接收到任何内容。我的代码看起来真的和asio代码相当。为什么会失败?

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

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

用修复

auto socket = acceptor.accept(io_context);

最新更新