elhayra / tcp_server_client

A thin and simple C++ TCP client server
MIT License
155 stars 53 forks source link

automatic client reconnect #13

Closed IOTeule closed 2 years ago

IOTeule commented 2 years ago

Tried this client code for automatic reconnect, but fails. State isConnected() seems to be detected incorrectly.

while (1) {
if (client.isConnected()) {
std::cout << "Client connected successfully\n";
// send() } else { std::cout << "connect ... \n";
client.connectTo("127.0.0.1", 3000); } sleep(1); };

Would be glad to hear about your expert recommendation?

elhayra commented 2 years ago

you're using the same "disconnected" client object after its socket have been closed. Once the socket is closed, it can't be reopened. In order to reconnect, just create a new client instance, and pass the same connection details to it.