boost::asio and socket ownership
Asked Answered
G

3

3

I've two classes (Negotiator, Client), both has their own boost::asio::ip::tcp::socket. Is there a way to transfer socket object to Client after negotiation is finished. I'm looking forward to do something like that:

 boost::asio::ip::tcp::socket sock1(io);
 //...
 boost::asio::ip::tcp::socket sock2;
 sock2.assign(sock1); 

This operation must guarantee that the connection won't be closed when sock1 is destroyed.

Grevera answered 3/6, 2010 at 13:23 Comment(0)
A
2

I think that you could:

  • obtain sock1's native handle with the native() member function
  • dup() (or WSADuplicateSocket()) sock1's native handle
  • pass the dup()-ed handle to sock2 with the assing() member function

However:

  • I'm not sure as I never tried that
  • If you want to transfer (instead of sharing) the socket from Negotiator to Client, Dan's suggestion of using dynamic allocation is probably simpler, using unique_ptr (or auto_ptr)
Alter answered 3/6, 2010 at 18:36 Comment(0)
T
2

Create the socket on the heap (new), and pass the pointer from the negotiator to the client.

Tannertannery answered 3/6, 2010 at 15:47 Comment(1)
This doesn't help in the case of accepting a plain TCP socket and then wanting to turn it into an ssl socket. Then you truly need to pull the internal socket out of the first and stick it into the second.Substrate
A
2

I think that you could:

  • obtain sock1's native handle with the native() member function
  • dup() (or WSADuplicateSocket()) sock1's native handle
  • pass the dup()-ed handle to sock2 with the assing() member function

However:

  • I'm not sure as I never tried that
  • If you want to transfer (instead of sharing) the socket from Negotiator to Client, Dan's suggestion of using dynamic allocation is probably simpler, using unique_ptr (or auto_ptr)
Alter answered 3/6, 2010 at 18:36 Comment(0)
R
0

As of the current version of Boost, you would now get the handle with

boost::asio::ip::tcp::socket::my_socket;
auto my_handle = my_socket.native_handle();

instead of the old native() member function.

Recusant answered 13/2, 2018 at 0:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.