Reputation: 920
I'm using Socket
to connect to a server. I'm having variable timeouts depending on the options I'm executing. I want to be able to retry the connect()
method at least 3 times before informing the client that the connection couldn't be opened.
I've try wrapping the connect()
method in a try/catch
and recalling connect()
when the exception caught is SocketTimeoutException
, but this hasn't worked. I know the answer probably involves putting the whole process inside a for/while
loop, but I can't seem to figure out how.
Any help?
Upvotes: 1
Views: 1010
Reputation: 3852
Something like this, maybe:
private void doSomething() {
Socket socket = null;
for (int i = 0; i < 3; i++) {
try {
socket = connectToServer();
break;
} catch (IOException e) {
// Log exception,
// show message to user,
// etc.
}
}
if (socket != null) {
// Ok
} else {
// Could not connect to server.
}
}
private Socket connectToServer() throws IOException {
// Always returns a valid socket.
// Throws exception in case of problems.
}
Upvotes: 1