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);