Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing around boost::asio::ip::tcp::socket

Alright, this is my current code snippet:

namespace bai = boost::asio::ip;
bai::tcp::socket tcp_connect(std::string hostname, std::string port) {
    try {
        boost::asio::io_service io_service;
        bai::tcp::resolver resolver(io_service);

        // we now try to get a list of endpoints to the server 
        bai::tcp::resolver::query query(hostname, port);
        bai::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
        bai::tcp::resolver::iterator end;

        // looking for a successful endpoint connection
        bai::tcp::socket socket(io_service);
        boost::system::error_code error = boost::asio::error::host_not_found;
        while (error && endpoint_iterator != end) {
            socket.close();
            socket.connect(*endpoint_iterator++ , error);
        }

        if (error) throw boost::system::system_error(error);

        return socket;
    } catch (std::exception &ex) {
        std::cout << "Exception: " << ex.what() << "\n";
    }
}

Which should return a boost::asio::ip::tcp::socket connected to hostname on port. However I get presented with a shitload of incomprehensible boost::noncopyable errors. But my question is, how should I pass around these sockets then? What's wrong with this?

like image 881
orlp Avatar asked Mar 24 '11 21:03

orlp


1 Answers

socket can't be copied. Use a boost::shared_ptr<bai::tcp::socket> instead. If you could copy a socket you'd have all sorts of funny issues if you ended up with two socket instances representing the same underlying OS socket - so it makes sense that copying (and therefore return by value, pass by value) is not allowed.

like image 130
Erik Avatar answered Oct 24 '22 01:10

Erik