Selector selector = Selector.open();
try {
SelectionKey key = channel.register(selector,
SelectionKey.OP_CONNECT);
Period timeRemaining = connectionTimeout;
Time startTime = clock.getCurrentTime();
boolean connected = false;
while (!connected) {
long timeout = timeRemaining.inMillisTreatIndefinitelyAsZero();
int keys = selector.select(timeout);
if (keys == 0) {
// Selector woken up, check to see whether it has timed out.
Time now = clock.getCurrentTime();
Period elapsed = now.getPeriodSince(startTime);
if (Comparator.GE.compare(
elapsed, timeRemaining)) {
// Timed out so fail.
throw new ConnectException("Timed out");
} else {