Tomáš Zato
Tomáš Zato

Reputation: 53161

Reinitialise asio::socket in class

I found out, that if I want to use boost::socket as a class member I must define it using initialization lists and it must be defined even before constructor dispatches.
That means, that I have to prove its constructor with some dummy parameter and I will need to reinitialise it again, when I have data I need.

client.hpp

class SocketClient {
    private:
       int port; //Port, currently unused
       boost::asio::io_service io_service;  //This is my "dummy" parameter
       boost::asio::ip::tcp::resolver::iterator endpoint_iterator;
       boost::asio::ip::tcp::socket sock; //Socket class instance
     
    public:
       void init(const char*, const char* );
       SocketClient::SocketClient():sock(io_service){};  //Giving empty "io_service" to  the "sock"
       bool read(int bytes, char *text);
       bool send(int length, char *text);
       bool send(std::string text);
       unsigned int timeout;
};

Later, when init() method is called, I need to supply the sock with initialised io_service. I have no idea how to do this:

client.h

void SocketClient::init(const char* ip_a, const char* port_a) {
    boost::asio::ip::tcp::resolver resolver(io_service);
    boost::asio::ip::tcp::resolver::query query(ip_a, port_a);
    boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    //Error (unsuported operator =):
    sock=boost::asio::ip::tcp::socket(io_service);
    //Error (term does not evaluate to a function taking 1 arguments):
    sock(io_service);
}

Here you can see whole project, with nothing removed.

Upvotes: 0

Views: 1440

Answers (1)

Shmil The Cat
Shmil The Cat

Reputation: 4668

You already have the sokect initialized , now only need to connect

tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(), ip_a,port_a);
tcp::resolver::iterator iterator = resolver.resolve(query);
sock.connect(*iterator);

Upvotes: 2

Related Questions