I am following Boost UDP multicast sender tutorial here . I modify it to make a class as follow:
#define _CRT_SECURE_NO_WARNINGS
#include <ctime>
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
using boost::asio::ip::udp;
using std::cout;
using std::cin;
using std::endl;
class sender
{
private:
boost::asio::io_context io_context;
boost::asio::ip::udp::endpoint endpoint_;
boost::asio::ip::udp::socket socket_;
int message_count_;
std::string message_;
bool showBroadcast;
public:
// constructor
sender(std::string multicast_address, unsigned short multicast_port, bool show = true)
{
boost::asio::io_context io_context;
boost::asio::ip::udp::endpoint endpoint_(boost::asio::ip::make_address("192.168.0.255"), 13000);
boost::asio::ip::udp::socket socket_(io_context, endpoint_.protocol());
socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true)); // no need
}
// destructor
~sender()
{
cout << "UDP sender exiting." << endl;
}
private:
std::string get_input()
{
std::string result;
cout << "Enter your message: ";
getline(cin, result);
return result;
}
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
std::string result = ctime(&now);
return result.erase(result.length() - 1, 1);
}
std::string some_string()
{
std::string result;
result = make_daytime_string();
return result;
}
};
int main(int argc, char* argv[])
{
try
{
sender s("192.168.0.255", 13000);
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
I wish to encapsulate io_context object inside the class, rather than having it outside. VC++ complains:
boost::asio::basic_datagram_socket': no appropriate default constructor available
I believe it is trying to force me to have the constructor as follow (which I try to move away from):
sender(boost::asio::io_context& io_context, const boost::asio::ip::address& multicast_address, unsigned short multicast_port, bool show = true)
: endpoint_(multicast_address, multicast_port),
socket_(io_context, endpoint_.protocol())
How can I possibly have everything encapsulate inside my class? Why does Boost force me to do the other way? Please help. Thank you so much.
This seems to be due to io_context being non-copyable as suggested here . I wish to have this class copyable. Any idea?