tags:

views:

120

answers:

3

im trying to implement a client app with an asynchronous connection. i want to know if i can reuse a SocketChannel object after it has failed to connect to a server.

 SocketChannel channel = SocketChannel.open();
 channel.configureBlocking(false);
 InetSocketAddress addr = new InetSocketAddress(host, port);
 SelectionKey key = channel.register(select, SelectionKey.OP_READ, connection);
 channel.connect(addr);

after this is the select loop, my socket eventually gets selected because the connection failed. i would like to queue another connection attempt on that channel, and nothing i do seems to do it. the channel.isConnectionPending() method always returns true (even if i try to finishConnect)

is the only solution do get rid of this SocketChannel and create a new one?

A: 

Hmmm... I'm no NIO expert but something looks fishy. You are registering for OP_ACCEPT, which occurs when a listening channel receives an incoming connection -- however, you're using the channel for an outgoing connection.

You should post more of the code, including the select loop.

Jim Garrison
ahh sorry, copy and paste from another method in the codefixed.
aepurniet
ill post more code, but the question is pretty specific, can i call connect on a socket channel twice. all the code in the world isnt gonna shed more light on that. (well besides the sdk code, hmmm...)
aepurniet
+1  A: 

Sun has released the Java 6.0 sources under the GPL. "Read the source Luke"

And my reading of the code is that you cannot call connect a second time.

Stephen C
yeah it seems that once the state reaches pending there are no statements to get it back to unconnected.
aepurniet
A: 

Try it and see?

I'm not 100% sure, but I suspect you can once finishConnect has been called and returned or an exception from it thrown it may be ok.

Put a try/catch block around the connect and when the exception is caught you may be safe to call the channel.connect method again.

If it doesn't work then the answer is probably no.

Matt H