[英]C++ UDP Server io_context running in thread exits before work can start
我是 C++ 的新手,但到目前为止,大多数 asio 内容都是有意义的。 然而,我正在努力让我的 UDPServer 工作。
我的问题可能类似于: Trying to write UDP server class, io_context doesn't block
我认为我的 UDPServer 在可以将工作交给它的 io_context 之前就停止了。 但是,我在调用 io_context.run() 之前向上下文发布工作,所以我不明白为什么。
当然,我不完全确定我的上述陈述是否正确,希望得到一些指导。 这是我的 class:
template<typename message_T>
class UDPServer
{
public:
UDPServer(uint16_t port)
: m_socket(m_asioContext, asio::ip::udp::endpoint(asio::ip::udp::v4(), port))
{
m_port = port;
}
virtual ~UDPServer()
{
Stop();
}
public:
// Starts the server!
bool Start()
{
try
{
// Issue a task to the asio context
WaitForMessages();
m_threadContext = std::thread([this]() { m_asioContext.run(); });
}
catch (std::exception& e)
{
// Something prohibited the server from listening
std::cerr << "[SERVER @ PORT " << m_port << "] Exception: " << e.what() << "\n";
return false;
}
std::cout << "[SERVER @ PORT " << m_port << "] Started!\n";
return true;
}
// Stops the server!
void Stop()
{
// Request the context to close
m_asioContext.stop();
// Tidy up the context thread
if (m_threadContext.joinable()) m_threadContext.join();
// Inform someone, anybody, if they care...
std::cout << "[SERVER @ PORT " << m_port << "] Stopped!\n";
}
void WaitForMessages()
{
m_socket.async_receive_from(asio::buffer(vBuffer.data(), vBuffer.size()), m_endpoint,
[this](std::error_code ec, std::size_t length)
{
if (!ec)
{
std::cout << "[SERVER @ PORT " << m_port << "] Got " << length << " bytes \n Data: " << vBuffer.data() << "\n" << "Address: " << m_endpoint.address() << " Port: " << m_endpoint.port() << "\n" << "Data: " << m_endpoint.data() << "\n";
}
else
{
std::cerr << "[SERVER @ PORT " << m_port << "] Exception: " << ec.message() << "\n";
return;
}
WaitForMessages();
}
);
}
void Send(message_T& msg, const asio::ip::udp::endpoint& ep)
{
asio::post(m_asioContext,
[this, msg, ep]()
{
// If the queue has a message in it, then we must
// assume that it is in the process of asynchronously being written.
bool bWritingMessage = !m_messagesOut.empty();
m_messagesOut.push_back(msg);
if (!bWritingMessage)
{
WriteMessage(ep);
}
}
);
}
private:
void WriteMessage(const asio::ip::udp::endpoint& ep)
{
m_socket.async_send_to(asio::buffer(&m_messagesOut.front(), sizeof(message_T)), ep,
[this, ep](std::error_code ec, std::size_t length)
{
if (!ec)
{
m_messagesOut.pop_front();
// If the queue is not empty, there are more messages to send, so
// make this happen by issuing the task to send the next header.
if (!m_messagesOut.empty())
{
WriteMessage(ep);
}
}
else
{
std::cout << "[SERVER @ PORT " << m_port << "] Write Header Fail.\n";
m_socket.close();
}
});
}
void ReadMessage()
{
}
private:
uint16_t m_port = 0;
asio::ip::udp::endpoint m_endpoint;
std::vector<char> vBuffer = std::vector<char>(21);
protected:
TSQueue<message_T> m_messagesIn;
TSQueue<message_T> m_messagesOut;
Message<message_T> m_tempMessageBuf;
asio::io_context m_asioContext;
std::thread m_threadContext;
asio::ip::udp::socket m_socket;
};
}
现在在主 function 中调用代码:
enum class TestMsg {
Ping,
Join,
Leave
};
int main() {
Message<TestMsg> msg; // Message is a pretty basic struct that I'm not using yet. When I was, I was only receiving the first 4 bytes - which led me down this path of investigation
msg.id = TestMsg::Join;
msg << "hello";
UDPServer<Message<TestMsg>> server(60000);
}
调用时,服务器会在有机会打印“[SERVER] Started”之前立即退出
我将尝试按照链接帖子的描述添加工作守卫,但我仍然想了解为什么 io_context 没有足够快地准备好工作。
更新(现在我还阅读了问题,而不仅仅是代码)在WaitForMessages
中,您确实通过从 function 调用m_socket.async_receive_from
开始监听,因为它是异步的,function 将在设置监听后立即返回/解锁。 因此,只要您实际上没有客户端向您发送内容,您的服务器就无能为力。 只有当它收到一些东西时,回调才会被调用io_context::run
的线程调用。 所以你需要工作守卫,这样你的线程运行run
就不会在启动后立即解除阻塞,而是只要工作守卫在那里就会阻塞。 如果在处理程序中抛出异常并且您仍想继续使用您的服务器,通常它还会与 try/while 模式结合使用。
同样在您发布的代码中,您实际上从未调用UDPServer::Start
!
这是我对答案的第一个想法:
这是 ASIO 的正常行为。 io_context::run
function 将在没有工作要做时立即返回。
因此,要更改run
function 的行为以阻止您必须使用boost::asio::executor_work_guard<boost::asio::io_context::executor_type>
即所谓的工作守卫。 使用对您的 io_context 的引用构造io_context
并保持它,即不要让它破坏,只要您想让服务器运行,即不想让io_context::run
在没有工作时返回。
所以给出
boost::asio::io_context io_context_;
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work_guard_;
然后你可以打电话
work_guard_{boost::asio::make_work_guard(io_context_)},
const auto thread_count{std::max<unsigned>(std::thread::hardware_concurrency(), 1)};
std::generate_n(std::back_inserter(this->io_run_threads_),
thread_count,
[this]() {
return std::thread{io_run_loop,
std::ref(this->io_context_), std::ref(this->error_handler_)};
});
void io_run_loop(boost::asio::io_context &context,
const std::function<void(std::exception &)> &error_handler) {
while (true) {
try {
context.run();
break;
} catch (std::exception &e) {
error_handler(e);
}
}
}
然后关闭服务器:
work_guard_.reset();
io_context_.stop();
std::for_each(this->io_run_threads_.begin(), this->io_run_threads_.end(), [](auto &thread) {
if (thread.joinable()) thread.join();
});
为了更优雅地关闭,您可以省略stop
调用,而是关闭之前的所有 sockets。
看起来你忘了打电话给server.Start();
. 此外,您需要让主线程等待一段时间,否则Server
的析构函数将立即导致Stop()
被调用:
int main()
{
Message<TestMsg> msg;
msg.id = TestMsg::Join;
msg << "hello";
UDPServer<Message<TestMsg>> server(60000);
server.Start();
std::this_thread::sleep_for(30s);
}
Send
API 存在一个概念性问题。它在每次调用时都需要一个端点,但它只使用启动写入调用链的端点! 这意味着如果你这样做
srv.Send(msg1, {mymachine, 60001}); srv.Send(msg1, {otherserver, 5517});
它们很可能都被发送到 mymachine:60001。
你如何对待收到的缓冲区。 只是盲目地使用.data()
假设数据是 NUL 终止的。 不要那样做:
std::string const data(vBuffer.data(), length);
此外,您似乎有时对数据和打印m_endpoint.data()
感到困惑 - 您的公主在另一座城堡中。
实际上,您可能想要提取类型化数据的方法。 我将其保留在今天这个问题的 scope 之外。
无论如何,您应该在重用之前清除缓冲区,因为您可能会在后续读取中看到旧数据。
vBuffer.assign(vBuffer.size(), '\0');
这很可能是未定义的行为:
asio::buffer(&m_messagesOut.front(), sizeof(message_T)), ep,
这仅在message_T
是微不足道且标准布局(“POD” - 普通旧数据)时有效。 operator<<
的存在强烈表明情况并非如此。
相反,构建一个(序列)缓冲区帽子将消息表示为原始字节,例如
auto& msg = m_messagesOut.front(); msg.length = msg.body.size(); m_socket.async_send_to( std::vector<asio::const_buffer>{ asio::buffer(&msg.id, sizeof(msg.id)), asio::buffer(&msg.length, sizeof(msg.length)), asio::buffer(msg.body), }, //...
线程安全队列似乎有点矫枉过正,因为您只有一个服务线程; 那是一个隐式的“链”,因此您可以将其发布到它以具有单线程语义。
到目前为止,这里有一些改编以使其工作(除了读者练习指出的):
#include <boost/asio.hpp>
#include <iostream>
#include <deque>
#include <sstream>
// Library facilities
namespace asio = boost::asio;
using asio::ip::udp;
using boost::system::error_code;
using namespace std::chrono_literals;
/////////////////////////////////
// mock ups:
template <typename message_T> struct Message {
message_T id;
uint16_t length; // automatically filled on send, UDP packets are < 64k
std::string body;
template <typename T> friend Message& operator<<(Message& m, T const& v)
{
std::ostringstream oss;
oss << v;
m.body += oss.str();
//m.body += '\0'; // suggestion for easier message extraction
return m;
}
};
// Thread-safety can be replaced with the implicit strand of a single service
// thread
template <typename T> using TSQueue = std::deque<T>;
// end mock ups
/////////////////////////////////
template <typename message_T> class UDPServer {
public:
UDPServer(uint16_t port)
: m_socket(m_asioContext, udp::endpoint(udp::v4(), port))
{
m_port = port;
}
virtual ~UDPServer() { Stop(); }
public:
// Starts the server!
bool Start()
{
if (m_threadContext.joinable() && !m_asioContext.stopped())
return false;
try {
// Issue a task to the asio context
WaitForMessages();
m_threadContext = std::thread([this]() { m_asioContext.run(); });
} catch (std::exception const& e) {
// Something prohibited the server from listening
std::cerr << "[SERVER @ PORT " << m_port
<< "] Exception: " << e.what() << "\n";
return false;
}
std::cout << "[SERVER @ PORT " << m_port << "] Started!\n";
return true;
}
// Stops the server!
void Stop()
{
// Tell the context to stop processing
m_asioContext.stop();
// Tidy up the context thread
if (m_threadContext.joinable())
m_threadContext.join();
// Inform someone, anybody, if they care...
std::cout << "[SERVER @ PORT " << m_port << "] Stopped!\n";
m_asioContext
.reset(); // required in case you want to reuse this Server object
}
void Send(message_T& msg, const udp::endpoint& ep)
{
asio::post(m_asioContext, [this, msg, ep]() {
// If the queue has a message in it, then we must
// assume that it is in the process of asynchronously being written.
bool bWritingMessage = !m_messagesOut.empty();
m_messagesOut.push_back(msg);
if (!bWritingMessage) {
WriteMessage(ep);
}
});
}
private:
void WaitForMessages() // assumed to be on-strand
{
vBuffer.assign(vBuffer.size(), '\0');
m_socket.async_receive_from(
asio::buffer(vBuffer.data(), vBuffer.size()), m_endpoint,
[this](std::error_code ec, std::size_t length) {
if (!ec) {
std::string const data(vBuffer.data(), length);
std::cout << "[SERVER @ PORT " << m_port << "] Got "
<< length << " bytes \n Data: " << data << "\n"
<< "Address: " << m_endpoint.address()
<< " Port: " << m_endpoint.port() << "\n"
<< std::endl;
} else {
std::cerr << "[SERVER @ PORT " << m_port
<< "] Exception: " << ec.message() << "\n";
return;
}
WaitForMessages();
});
}
void WriteMessage(const udp::endpoint& ep)
{
auto& msg = m_messagesOut.front();
msg.length = msg.body.size();
m_socket.async_send_to(
std::vector<asio::const_buffer>{
asio::buffer(&msg.id, sizeof(msg.id)),
asio::buffer(&msg.length, sizeof(msg.length)),
asio::buffer(msg.body),
},
ep, [this, ep](std::error_code ec, std::size_t length) {
if (!ec) {
m_messagesOut.pop_front();
// If the queue is not empty, there are more messages to
// send, so make this happen by issuing the task to send the
// next header.
if (!m_messagesOut.empty()) {
WriteMessage(ep);
}
} else {
std::cout << "[SERVER @ PORT " << m_port
<< "] Write Header Fail.\n";
m_socket.close();
}
});
}
private:
uint16_t m_port = 0;
udp::endpoint m_endpoint;
std::vector<char> vBuffer = std::vector<char>(21);
protected:
TSQueue<message_T> m_messagesIn;
TSQueue<message_T> m_messagesOut;
Message<message_T> m_tempMessageBuf;
asio::io_context m_asioContext;
std::thread m_threadContext;
udp::socket m_socket;
};
enum class TestMsg {
Ping,
Join,
Leave
};
int main()
{
UDPServer<Message<TestMsg>> server(60'000);
if (server.Start()) {
std::this_thread::sleep_for(3s);
{
Message<TestMsg> msg;
msg.id = TestMsg::Join;
msg << "hello PI equals " << M_PI << " in this world";
server.Send(msg, {{}, 60'001});
}
std::this_thread::sleep_for(27s);
}
}
出于某种原因,.netcat 不适用于 Coliru 上的 UDP,所以这里有一个“实时”演示:
您可以看到我们的 .netcat 客户端消息到达。 您可以在 tcpdump output 中看到发送到 60001 的消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.