What's the proper way to use SocketChannel.finishConnect()?

?

-

What's the proper way to use SocketChannel.finishConnect()?

I've read the documentation but couldn't comprehend what is written for it.

I've seen examples where it is placed:

1a) Right after SocketChannel.connect() (without while loop)

SocketChannel sc = SocketChannel.open();
sc.connect(...);
sc.finishConnect();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);

1b) Right after SocketChannel.connect() (with while loop)

SocketChannel sc = SocketChannel.open();
sc.connect(...);
while (!sc.finishConnect()) {
}
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);


2a) When iterating the Selector.select() values (without while loop;

SocketChannel sc = SocketChannel.open();
sc.connect(...);
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_CONNECT);

.... {

if (sc.isConnectionPending()) {
sc.finishConnect();
}

sc.register(selector, SelectionKey.OP_READ);
}
....

2b) When iterating the Selector.select() values (with while loop)

SocketChannel sc = SocketChannel.open();
sc.connect(...);
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_CONNECT);

.... {

if (sc.isConnectionPending()) {
while (!sc.finishConnect()) {
}
}

sc.register(selector, SelectionKey.OP_READ);
}
....
 
E

Esmond Pitt

- said:
What's the proper way to use SocketChannel.finishConnect()?

[examples snipped]

None of the above. If you call connect() while in blocking mode you
don't need finishConnect() at all. If you call it in non-blocking mode
you can either loop while (!socketChannel.finishConnect()) ; (preferably
doing something useful) or register for OP_CONNECT and call
finishConnect() when it fires. If OP_CONNECT fires, finishConnect()
should return true for that channel. Don't forget to deregister for
OP_CONNECT when it fires, otherwise it will get mixed up with OP_WRITE.

SocketChannel.isConnectionPending() only tells you whether you have
called connect() in non-blocking mode and not yet had a 'true' from
finishConnect(), and you don't really need to call it in any of the
scenarios above as you already know that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top