How to tell if a server is not available when connecting via TCP/IP

R

Rick

Hi,

I'm trying to connect to a server application listening on a particular
port. Soemtimes what happens is that the server crashes for some reason
and when my client application tries to create a Socket object from the
server's IP and PORT, an exception is thrown: java.net.ConnectException:
Connection refused: connect.

How can I tell that a server is not available before creating a socket?
And how do I cleanly "continue" from the point where the exception is
being thrown? Thanks!

-Rick
 
D

Dobromir Gaydarov

Just catch the exception and do whatever you want to do when the server is
not available.
You do not have to prevent checked exceptions from happening (you cannot),
you just have to write code to handle them.

I do not understand "cleanly", but seems you look at the exceptions as being
errors.
If that is the case you are confused - the exceptions are good thing:
- they are there to force you to thing about exceptional cases
- they allow you to write code for the normal case first, then consider the
"other" cases.

Dobromir
 
G

Gordon Beaton

when my client application tries to create a Socket object from the
server's IP and PORT, an exception is thrown:
java.net.ConnectException: Connection refused: connect.

How can I tell that a server is not available before creating a
socket?

You can't. The only way to tell whether it's available is to try to
connect to it.

Even if there were another way, there would be no guarantee that the
server is still up when you actually try to connect (even a fraction
of a second later), so you've still got to handle that possibility
anyway.
And how do I cleanly "continue" from the point where the exception
is being thrown? Thanks!

That really depends what you want to do when the connection attempt
fails. What can your application do without the connection?

Here's one possibility, retry the attempt a few times before giving
up:

int attempts = 5;
Socket s = null;

while (s == null) {
try {
s = new Socket(...);
}
catch (IOException e) {
if (--attempts == 0) {
throw e;
else {
try {
Thread.sleep(5000);
}
catch (InterruptedException f) {
// ignore
}
}
}
}

// here, s is connected

/gordon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top