I have a client that is talking to a server. I want to use nonblocking
sockets. The client connects fine, so long as the server is already
up. But the client doesn't connect if the server isn't already up (of
course). Assuming that the server isn't up, I want the client to wait
a few seconds and try again. But for some reason, in my code, once the
client has failed to connect once, further attempts always fail. In
other words, in the code below, finishConnect() should return true once
a connection has been established. If the server is already up, it
does return true, and everything works. If the server is down,
finishConnect() returns false (as it should). But then subsequent
calls to it always return false, so the connection is never
established. Any idea what I'm doing wrong? What is the proper way to
use this?
Thanks!
//Create a socket to connect to teh server
InetSocketAddress InternetSocketAddress = new
InetSocketAddress(ServerAddress, Port);
SocketChannel ClientSocketChannel = null;
try{
ClientSocketChannel = SocketChannel.open();
ClientSocketChannel.configureBlocking(false);
}catch (IOException Exception) {
System.out.println("Could not open SocketChannel on
client");
System.exit(-1);
}
try{
ClientSocketChannel.connect(InternetSocketAddress);
}catch (IOException Exception) {
System.out.println("Could not connect to server");
}
Boolean ConnectedToRemoteHost = false;
while (ConnectedToRemoteHost == false){
try{
//THE NEXT LINE ALWAYS RETURNS FALSE, UNLESS IT
SUCCEEDS
//ON THE FIRST TRY!
ConnectedToRemoteHost =
ClientSocketChannel.finishConnect();
}catch (IOException e){
System.out.println("client failed to connect");
}
}
Oliver Wong - 07 Apr 2006 22:52 GMT
>I have a client that is talking to a server. I want to use nonblocking
> sockets. The client connects fine, so long as the server is already
[quoted text clipped - 43 lines]
> }
> }
Are sure sure that line always returns false? Are you sure the line
doesn't actually complete because an exception is being thrown?
- Oliver
Gordon Beaton - 08 Apr 2006 09:46 GMT
> If the server is down, finishConnect() returns false (as it should).
> But then subsequent calls to it always return false, so the
> connection is never established.
Instead of calling finishConnect() repeatedly, I'd recommend using a
Selector to tell you when it's time to call finishConnect().
/gordon

Signature
[ do not email me copies of your followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e