Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "pch.h"
- #include "UdpClient.h"
- #include <boost/throw_exception.hpp>
- #include <boost/array.hpp>
- #include <boost/bind.hpp>
- #include <boost/make_shared.hpp>
- static int PortIn = 32677;
- static int PortOut = 32676;
- static std::string Loopback = "127.0.0.1";
- // ReSharper disable once CppPossiblyUninitializedMember
- UdpClient::UdpClient() // NOLINT
- {
- try
- {
- _endpointIn = std::make_shared<udp::endpoint>(address::from_string("0.0.0.0"), PortIn);
- }
- catch (std::exception const& e)
- {
- var wut = e.what();
- std::cout << wut << std::endl;
- }
- _endpointOut = std::make_shared<udp::endpoint>(address::from_string(Loopback), PortOut);
- try
- {
- _socketIn = std::make_shared<udp::socket>(_ioServiceIn, *_endpointIn.get());
- }
- catch (std::exception const& e)
- {
- var wut = e.what();
- std::cout << wut << std::endl;
- }
- _socketOut = std::make_shared<udp::socket>(_ioServiceOut, *_endpointOut.get());
- }
- void UdpClient::Init(const bool isInput)
- {
- if (!isInput)
- {
- _ioServiceOut.run();
- return;
- }
- StartReceive();
- _ioServiceIn.run();
- }
- UdpClient::~UdpClient() // NOLINT
- {
- _socketIn->close();
- _socketOut->close();
- }
- void UdpClient::Send(std::string message)
- {
- _socketOut->send_to(
- boost::asio::buffer(message), *(_endpointOut.get())
- );
- }
- void UdpClient::Send(int i)
- {
- MFiflak fif;
- fif.I = i;
- boost::array<char, 4> buff = { fif.C[0], fif.C[1], fif.C[2], fif.C[3] };
- std::cout << "Sending data to: " << _endpointOut->address().to_string() << " at port " << _endpointOut->port() << std::endl;
- _socketOut->send_to(
- boost::asio::buffer(buff), *(_endpointOut.get())
- );
- }
- boost::signals2::signal<void(double *, int)>* UdpClient::GetIncomer()
- {
- return &_incoming;
- }
- boost::signals2::signal<void(std::string)>* UdpClient::GetStringIncomer()
- {
- return &_stringIncoming;
- }
- void UdpClient::StartReceive()
- {
- _socketIn->async_receive_from(
- boost::asio::buffer(_bufferIn), *_endpointIn.get(),
- 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)
- {
- const var mSize = sizeof(double) * COMM_COUNT;
- if (bytesTransferred != mSize)
- {
- const std::string message(_bufferIn.data() + sizeof(double), _bufferIn.data() + bytesTransferred);
- //Incoming String
- }
- else {
- for (var i = 0; i < _bufferIn.size(); i += mSize)
- {
- Command comm;
- for (var j = 0; j < mSize; j++)
- comm.C[j] = _bufferIn[i + j];
- if (comm.D[0] == 5.0)
- {
- const std::string message(_bufferIn.data() + sizeof(double), _bufferIn.data() + bytesTransferred);
- //Incoming String
- }
- else
- {
- _incoming(comm.D, COMM_COUNT);
- }
- }
- }
- }
- StartReceive();
- }
Advertisement
Add Comment
Please, Sign In to add comment