gpt4 book ai didi

c++ - 如何使用专用线程接收UDP数据?

转载 作者:行者123 更新时间:2023-11-28 01:22:13 25 4
gpt4 key购买 nike

我想使用专用线程使用 asio 库接收 udp 数据。下面给出了示例代码。

#define ASIO_STANDALONE // we are using the stand aloe version of ASIO and Not Boost::ASIO


#include <iostream>
#include "include/asio.hpp"
#include <array>
#include <thread>


class UDPServer
{

public:
UDPServer( asio::io_service& ioService): m_socket(ioService)
{}
~UDPServer(){}

void listen(const int& port)
{
m_socket.open(asio::ip::udp::v4());
m_socket.bind(asio::ip::udp::endpoint(asio::ip::udp::v4(), port));

#define DEDICATED_THREAD_FLAG 1

#if DEDICATED_THREAD_FLAG
m_thread = std::thread( &UDPServer::receive, this);
std::cout<<"Thead Id in listen:"<<std::this_thread::get_id()<<std::endl;
m_thread.join();
#else
receive();
#endif
}

template<std::size_t SIZE>
void processReceivedData(const std::array<char, SIZE>& rcvdMessage,
const int& rcvdMessageSizeInBytes,
const std::error_code& error)
{

std::cout<<"Rcvd Message: "<<rcvdMessage.data()<<std::endl;
receive();

}
void receive()
{
std::cout<<"Thead Id in receive0:"<<std::this_thread::get_id()<<std::endl;

asio::ip::udp::endpoint m_udpRemoteEndpoint;

m_socket.async_receive_from(asio::buffer(recv_buffer, recv_buffer.size()/*NetworkBufferSize*/), m_udpRemoteEndpoint,
[this](std::error_code ec, std::size_t bytesReceived)
{
std::cout<<"Thead Id in receive1:"<<std::this_thread::get_id()<<std::endl;

processReceivedData(recv_buffer, bytesReceived, ec);
});

}

private:
asio::ip::udp::socket m_socket;
std::thread m_thread;
static const int NetworkBufferSize = 9000;
std::array<char, NetworkBufferSize> recv_buffer;

};


int main()
{

std::cout<<"Main Thead Id:"<<std::this_thread::get_id()<<std::endl;
asio::io_service m_ioService;


UDPServer myServer( m_ioService);
myServer.listen(12345); // starting the UDP server

std::cout<<"Program waiting.."<<std::endl;

m_ioService.run();


std::cout<<"Program ending.."<<std::endl;
}

可以通过将 DEDICATED_THREAD_FLAG 更改为 0 来启用非专用线程版本,这会按预期工作。

但是,当 DEDICATED_THREAD_FLAG 设置为 1 时,一个新线程正在启​​动并进入“接收”函数。但是当 udp 数据包到达时,它仅由主线程处理,而不是由专用线程处理。

这里出了什么问题?

最佳答案

处理异步调用的整个事件循环由您在主线程中运行的 io_server 完成。

您应该运行io_service::run,而不是在线程中运行receive 函数(无论如何它都会立即返回)。

关于c++ - 如何使用专用线程接收UDP数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55586047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com