Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "pch.h"
- #include "UdpClient.h"
- #include <boost/bind.hpp>
- #include <boost/make_shared.hpp>
- static std::string PortIn = "32677";
- static std::string PortOut = "32676";
- static std::string Loopback = "127.0.0.1";
- // ReSharper disable once CppPossiblyUninitializedMember
- UdpClient::UdpClient() // NOLINT
- {
- _socketIn = boost::make_shared<udp::socket>(_ioServiceIn, udp::endpoint(udp::v4(), 0));
- _socketOut = boost::make_shared<udp::socket>(_ioServiceOut, udp::endpoint(udp::v4(), 0));
- }
- void UdpClient::Init(const bool isInput)
- {
- udp::resolver resolver((isInput ? _ioServiceIn : _ioServiceOut));
- const udp::resolver::query query(udp::v4(), Loopback, (isInput ? PortIn : PortOut));
- const udp::resolver::iterator it = resolver.resolve(query);
- if (!isInput) {
- _endpointOut = *it;
- _ioServiceOut.run();
- return;
- }
- _endpointIn = *it;
- StartReceive();
- _ioServiceIn.run();
- }
- UdpClient::~UdpClient() // NOLINT
- {
- _socketIn->close();
- _socketOut->close();
- }
- void UdpClient::Send(std::string message)
- {
- _socketOut->send_to(
- boost::asio::buffer(message, message.size()), _endpointOut
- );
- }
- void UdpClient::StartReceive()
- {
- _socketIn->async_receive_from(
- boost::asio::buffer(_bufferIn), _endpointIn,
- boost::bind(
- &UdpClient::Receive, this,
- boost::asio::placeholders::error,
- boost::asio::placeholders::bytes_transferred
- )
- );
- }
- void UdpClient::Receive(const boost::system::error_code& error, std::size_t bytesTransferred)
- {
- if (!error)
- {
- std::string message(_bufferIn.data(), _bufferIn.data() + bytesTransferred);
- Incoming(message);
- }
- StartReceive();
- }
Advertisement
Add Comment
Please, Sign In to add comment