Код: Выделить всё
class UDPBase
{
public:
using IoContext = boost::asio::io_service; // backwards compatibility forces me to use an older boost
using UDP = boost::asio::ip::udp;
using Socket = UDP::socket;
using Endpoint = UDP::endpoint;
using Address = boost::asio::ip::address;
using ErrorCode = boost::system::error_code;
public:
UDPBase(IoContext &ioContext);
UDPBase(IoContext &ioContext, unsigned short int listenPort);
virtual ~UDPBase();
virtual void startListening();
void startIoContext();
void stopIoContext();
protected:
void init();
virtual void close();
void doListen();
virtual void onDataReceived(const ErrorCode &ec, unsigned char *buffer, size_t bufferSize);
private:
IoContext &ioContext;
Socket socket;
Endpoint listeningEndpoint;
Endpoint destinationEndpoint;
};
< /code>
listeningEndpoint
Код: Выделить всё
UDPBase::UDPBase(IoContext &ioContext) : ioContext(ioContext), socket(ioContext)
{
init();
}
UDPBase::UDPBase(IoContext &ioContext, unsigned short int listenPort) : ioContext(ioContext), socket(ioContext)
{
// set listenEndpoint based on the port
init();
}
UDPBase::~UDPBase()
{
// close();
}
void UDPBase::startListening(unsigned short int listenPort)
{
init();
doListen();
}
void UDPBase::close()
{
socket.close();
}
void UDPBase::startIoContext()
{
ioContext.run();
}
void UDPBase::stopIoContext()
{
ioContext.post([this]()
{
if (socket.is_open())
{
socket.close();
}
});
ioContext.stop();
}
void UDPBase::doListen()
{
socket.async_receive_from(
boost::asio::buffer(receiveBuffer, maxBufferSize), listeningEndpoint,
[this](ErrorCode ec, std::size_t bytesRecvd)
{
// std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/79562201/udp-client-using-boost-does-not-always-receive-packets-though-i-can-see-them-in[/url]