【发布时间】:2020-05-23 04:29:54
【问题描述】:
我目前正在阅读一本名为“C++ Crash Course”的 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;
}
}
(注意:原始示例使用enable_shared_from_this 通过shared_ptr 将this 捕获到lambdas 中,但我故意省略了它以查看没有它会发生什么。)
我的代码无法编译,我觉得完全解析 error message 需要一千年的时间(因为它很大,所以发布在 pastebin.com 上)。
问题似乎是缓冲区的使用/构造方式错误,但我不知道这段代码到底有什么问题。这里关于 Asio 的几个答案要么使用 TCP,要么解决一个完全不同的问题,所以我犯的错误必须是非常基本的。我在 Asio 文档中没有找到任何相关内容。
公平地说,Asio 对我的新手来说似乎太复杂了。可能我现在还没有资格使用它。尽管如此,我仍然希望完成练习并继续前进。任何帮助将不胜感激。
【问题讨论】:
标签: c++ boost boost-asio