I'm calling SocketChannel.finishConnect, which is supposed to return
false unless a connection succeeds. However, when I try to connect, I
get a "connection refused" IOException. This makes sense, since the
server I'm trying to connect to is not up yet. But it has the side
effect of closing the channel! That means that I have to keep creating
a new SocketChannel and registering it with my Selector in the
exception handler until it actually connects. This seems like it
defeats the purpose of using a selector on a channel in the first
place.
My questions:
1) Why is the channel being closed? Shouldn't finishConnect just
return false so that I can try again?
2) Is there a way to prevent it from being closed?
3) Is there some alternative where I don't have to keep recreating a
re-registering the channel?
Thanks!
Gordon Beaton - 09 Apr 2006 09:22 GMT
> 1) Why is the channel being closed? Shouldn't finishConnect just
> return false so that I can try again?
> 2) Is there a way to prevent it from being closed?
> 3) Is there some alternative where I don't have to keep recreating a
> re-registering the channel?
A socket can only be used *once*. After the connection has failed, you
need to create a new one. This has really nothing to do with Java.
The connect()/finishConnect() mechanism is intended for the case when
connecting might take a long time, not when it might take many
attempts.
/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
EJP - 10 Apr 2006 01:58 GMT
> I'm calling SocketChannel.finishConnect, which is supposed to return
> false unless a connection succeeds. However, when I try to connect, I
[quoted text clipped - 12 lines]
> 3) Is there some alternative where I don't have to keep recreating a
> re-registering the channel?
As Gordon said in your other thread on the same topic, finishConnect()
should be called after OP_CONNECT has fired in a Selector. Using it any
other way doesn't work. If the connection fails the socket is useless
and must be discarded.
(Sun's documentation says 'this method may be invoked at any time' but
I'm not convinced that they really understand the underlying mechanism
or that they have ever tested this claim.)