You need to create a new boost::asio::ip::tcp::socket
each time you reconnect. The easiest way to do this is probably to just allocate the socket on the heap using a boost::shared_ptr
(you could probably also get away with scoped_ptr
if your socket is entirely encapsulated within a class). E.g.:
bool MyClient::myconnect()
{
bool isConnected = false;
// Attempt connection
// socket is of type boost::shared_ptr<boost::asio::ip::tcp::socket>
socket.reset(new boost::asio::ip::tcp::socket(...));
socket->connect(server_endpoint, errorcode);
// ...
}
Then, when mydisconnect
is called, you could deallocate the socket:
void MyClient::mydisconnect(void)
{
// ...
// deallocate socket. will close any open descriptors
socket.reset();
}
The error you’re seeing is probably a result of the OS cleaning up the file descriptor after you’ve called close
. When you call close
and then try to connect
on the same socket, you’re probably trying to connect an invalid file descriptor. At this point you should see an error message starting with “Connection failed: …” based on your logic, but you then call mydisconnect
which is probably then attempting to call shutdown
on an invalid file descriptor. Vicious cycle!