Nidrax

UdpClient.cpp

Sep 5th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. #include "pch.h"
  2. #include "UdpClient.h"
  3. #include <boost/bind.hpp>
  4. #include <boost/make_shared.hpp>
  5.  
  6. static std::string PortIn = "32677";
  7. static std::string PortOut = "32676";
  8. static std::string Loopback = "127.0.0.1";
  9.  
  10. // ReSharper disable once CppPossiblyUninitializedMember
  11. UdpClient::UdpClient()  // NOLINT
  12. {
  13.     _socketIn = boost::make_shared<udp::socket>(_ioServiceIn, udp::endpoint(udp::v4(), 0));
  14.     _socketOut = boost::make_shared<udp::socket>(_ioServiceOut, udp::endpoint(udp::v4(), 0));
  15. }
  16.  
  17. void UdpClient::Init(const bool isInput)
  18. {
  19.     udp::resolver resolver((isInput ? _ioServiceIn : _ioServiceOut));
  20.     const udp::resolver::query query(udp::v4(), Loopback, (isInput ? PortIn : PortOut));
  21.     const udp::resolver::iterator it = resolver.resolve(query);
  22.  
  23.     if (!isInput) {
  24.         _endpointOut = *it;
  25.         _ioServiceOut.run();
  26.         return;
  27.     }
  28.  
  29.     _endpointIn = *it; 
  30.     StartReceive();
  31.     _ioServiceIn.run();
  32. }
  33.  
  34. UdpClient::~UdpClient()  // NOLINT
  35. {
  36.     _socketIn->close();
  37.     _socketOut->close();
  38. }
  39.  
  40. void UdpClient::Send(std::string message)
  41. {
  42.     _socketOut->send_to(
  43.         boost::asio::buffer(message, message.size()), _endpointOut
  44.     );
  45. }
  46.  
  47. void UdpClient::StartReceive()
  48. {
  49.     _socketIn->async_receive_from(
  50.         boost::asio::buffer(_bufferIn), _endpointIn,
  51.         boost::bind(
  52.             &UdpClient::Receive, this,
  53.             boost::asio::placeholders::error,
  54.             boost::asio::placeholders::bytes_transferred
  55.         )
  56.     );
  57. }
  58.  
  59. void UdpClient::Receive(const boost::system::error_code& error, std::size_t bytesTransferred)
  60. {
  61.     if (!error)
  62.     {
  63.         std::string message(_bufferIn.data(), _bufferIn.data() + bytesTransferred);
  64.         Incoming(message);
  65.     }
  66.  
  67.     StartReceive();
  68. }
Advertisement
Add Comment
Please, Sign In to add comment