我目前正在浏览一本有关C ++的书,称为“ C ++速成课程”。关于网络的章节显示了如何使用Boost :: Asio编写一个简单的(同步或异步)大写TCP服务器。一项工作是用UDP重新创建它,这是我遇到的麻烦。这是我的实现:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/algorithm/string/case_conv.hpp>
using namespace boost::asio;
struct UdpServer {
explicit UdpServer(ip::udp::socket socket)
: socket_(std::move(socket)) {
read();
}
private:
void read() {
socket_.async_receive_from(dynamic_buffer(message_),
remote_endpoint_,
[this](boost::system::error_code ec, std::size_t length) {
if (ec || this->message_ == "\n") return;
boost::algorithm::to_upper(message_);
this->write();
}
);
}
void write() {
socket_.async_send_to(buffer(message_),
remote_endpoint_,
[this](boost::system::error_code ec, std::size_t length) {
if (ec) return;
this->message_.clear();
this->read();
}
);
}
ip::udp::socket socket_;
ip::udp::endpoint remote_endpoint_;
std::string message_;
};
int main() {
try {
io_context io_context;
ip::udp::socket socket(io_context, ip::udp::v4(), 1895);
UdpServer server(std::move(socket));
io_context.run();
} catch (std::exception & e) {
std::cerr << e.what() << std::endl;
}
}
(Note: The original example uses enable_shared_from_this
to capture this
by shared_ptr
into the lambdas, but I deliberately omitted it to see what would happen without it.)
My code does not compile, and I feel it will take me a thousand years to fully parse the error message (posted on pastebin.com since it's enormous).
似乎问题在于缓冲区的使用/构造方式错误,但是我不知道这段代码到底有什么问题。 SO上有关Asio的一些答案要么使用TCP要么解决一个完全不同的问题,所以我犯的错误必须是非常基本的。我没有在Asio文档中找到任何相关内容。
公平地说,对于我的新手来说,Asio似乎太复杂了。也许我现在没有资格使用它。尽管如此,我仍然想完成练习并继续前进。任何帮助,将不胜感激。
模板错误吐出了最丑陋的错误消息。您通常只需要检查编译器错误输出并在您自己的源文件中查找第一个引用。翼:
/home/atmaks/Code/CCC_chapter20/main.cpp:53:9: required from here
凝视它,并考虑您一生的所有决定,这些决定使您首先想要使用C ++进行开发。 :)
I can't for the life of me figure out how to get
dynamic_buffer
to work. It may simply be the case thatasync_read
doesn't like this type. Asio lacks proper documentation and leaves us with cryptic template types to figure out. And the only Asio documentation that is worthwhile are the decent examples - none of which referencedynamic_buffer
.因此,让我们更改为固定大小的缓冲区以进行接收。
当我们使用它时,它不喜欢您的套接字构造函数并引发异常。因此,我对其进行了修复,使其可以工作。
现在,为了证明它正在工作: