开发者

reusing socket channels

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();
    cha开发者_运维知识库nnel.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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜