简体   繁体   中英

Handling socket boost asio tcp ip - C++ socket programming

I am successfully establishing connection, sending and receiving messages using the following code. What I want to do is somehow to return that already established connection. I assume that I need to return the socket. Before writing this topic I read a few related topics - in some of them it was mentioned that returning a socket is not a good idea. Usage of shared is suggested here. Passing around boost::asio::ip::tcp::socket Unfortunately I am not familiar with this type of pointers and their usage. Could you help me with fixing that problem.

 try {
    boost::asio::io_service io_service;

    tcp::resolver resolver(io_service);
    tcp::resolver::query query(server, port);
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    my_socket = new tcp::socket(io_service);
    boost::system::error_code error = boost::asio::error::host_not_found;
    boost::asio::connect(*my_socket, endpoint_iterator);


    } catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
}

if you have c++11 or higher, ignore all that nonsense about shared pointers and return the socket. As of c++11 asio io objects support move construction and move assignment. An asio socket is extremely lighweight - the structure contains two pointers, nothing more. – Richard Hodges

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM