• Post Reply Bookmark Topic Watch Topic
  • New Topic

Testing a java.net.Socket for connectivity?  RSS feed

 
Scott Lynch
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any "standard" way of checking to see if a Socket object is still connected? e.g. - one that's fairly quick and non-costly? I arbitrarily tried calling getKeepAlive() like this:
public boolean isConnected()
{
try
{
socket.getKeepAlive();
}
catch(SocketException se) { return false; }
return true;
}
But that doesn't seem to work.. maybe this (?):
public boolean isConnected()
{
try
{
socket.getInputStream();
}
catch(SocketException se) { return false; }
return true;
}
 
Lewin Chan
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Scott,
socket.getKeepAlive() refers to the underlying TCP SO_KEEPALIVE parameter (which, if I actually made it past the introduction to any of W. Richard Stevens TCP/IP illustrated books, I'd be able to explain what that means).
Have you tried the various

methods in JDK1.4
If you're not on 1.4, then I think only way is to do as you suggested in your 2nd code example, if you really need to check that a socket is still open.
brgds
L
 
Scott Lynch
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Lewin Chan:
Scott,
socket.getKeepAlive() refers to the underlying TCP SO_KEEPALIVE parameter (which, if I actually made it past the introduction to any of W. Richard Stevens TCP/IP illustrated books, I'd be able to explain what that means).
Have you tried the various

methods in JDK1.4
If you're not on 1.4, then I think only way is to do as you suggested in your 2nd code example, if you really need to check that a socket is still open.
brgds
L

Unfortunatly I'm having to use 1.3 at the moment. My second section of code doesn't work either, actually.. a closed socket will still return an InputStream.
 
Michael Zalewski
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are two parts to a Socket, an InputStream and an OutputStream. Either half could be closed.
So the thing to test is the InputStream and OutputStream. Attempting to read(write) to these IOStreams will eventually give a SocketException.
The problem is that word 'eventually'. You can do some things like Socket.setSoTimeout(), InputStream.isAvailable(), etc. But I/O in Java is not real-time, meaning that the JVM makes no guarantees that any I/O call will come back in a predetermined length of time.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!