Reputation: 1978
I am trying to connect to a computer through a socket in c++. Basically what this code should do is try to connect, and if it cant connect, it should wait 3 seconds and try again.
while (true) {
if (connect(sock, (struct sockaddr *) &echoserver, sizeof(echoserver)) >= 0)
{
break;
}
cout << "Connection failed!";
sleep(3);
}
What the code does when its running is it will connect if it can, but if it can't, the cout
never gets called and sleep
never gets called either. When sleep
is not there, the program works and continually tries to connect to the socket but there is no delay so it wouldn't connect anyway. I really need the delay to work.
Could anyone please help?
Upvotes: 0
Views: 577
Reputation: 182779
Once the connect
fails, the socket refers to the failed connection. You can no longer use it to connect to anything. You need to close
the existing socket and allocate a new one. This would have been much easier to diagnose if you had reported the error in the cout
statement. (See docs for strerror
and errno
.)
Upvotes: 4