1 // Copyright (c) 2005 Brian Wellington (bwelling (at) xbill.org) 2 3 package org.xbill.DNS; 4 5 import java.io.*; 6 import java.net.*; 7 import java.nio.channels.*; 8 import org.xbill.DNS.utils.hexdump; 9 10 class Client { 11 12 protected long endTime; 13 protected SelectionKey key; 14 15 protected 16 Client(SelectableChannel channel, long endTime) throws IOException { 17 boolean done = false; 18 Selector selector = null; 19 this.endTime = endTime; 20 try { 21 selector = Selector.open(); 22 channel.configureBlocking(false); 23 key = channel.register(selector, SelectionKey.OP_READ); 24 done = true; 25 } 26 finally { 27 if (!done && selector != null) 28 selector.close(); 29 if (!done) 30 channel.close(); 31 } 32 } 33 34 static protected void 35 blockUntil(SelectionKey key, long endTime) throws IOException { 36 long timeout = endTime - System.currentTimeMillis(); 37 int nkeys = 0; 38 if (timeout > 0) 39 nkeys = key.selector().select(timeout); 40 else if (timeout == 0) 41 nkeys = key.selector().selectNow(); 42 if (nkeys == 0) 43 throw new SocketTimeoutException(); 44 } 45 46 static protected void 47 verboseLog(String prefix, byte [] data) { 48 if (Options.check("verbosemsg")) 49 System.err.println(hexdump.dump(prefix, data)); 50 } 51 52 void 53 cleanup() throws IOException { 54 key.selector().close(); 55 key.channel().close(); 56 } 57 58 } 59