01: // Copyright (c) 2005 Brian Wellington (bwelling@xbill.org)
02:
03: package org.xbill.DNS;
04:
05: import java.io.*;
06: import java.net.*;
07: import java.nio.*;
08: import java.nio.channels.*;
09:
10: final class UDPClient extends Client {
11:
12: public UDPClient(long endTime) throws IOException {
13: super (DatagramChannel.open(), endTime);
14: }
15:
16: void bind(SocketAddress addr) throws IOException {
17: DatagramChannel channel = (DatagramChannel) key.channel();
18: channel.socket().bind(addr);
19: }
20:
21: void connect(SocketAddress addr) throws IOException {
22: DatagramChannel channel = (DatagramChannel) key.channel();
23: channel.connect(addr);
24: }
25:
26: void send(byte[] data) throws IOException {
27: DatagramChannel channel = (DatagramChannel) key.channel();
28: verboseLog("UDP write", data);
29: channel.write(ByteBuffer.wrap(data));
30: }
31:
32: byte[] recv(int max) throws IOException {
33: DatagramChannel channel = (DatagramChannel) key.channel();
34: byte[] temp = new byte[max];
35: key.interestOps(SelectionKey.OP_READ);
36: try {
37: while (!key.isReadable())
38: blockUntil(key, endTime);
39: } finally {
40: if (key.isValid())
41: key.interestOps(0);
42: }
43: long ret = channel.read(ByteBuffer.wrap(temp));
44: if (ret <= 0)
45: throw new EOFException();
46: int len = (int) ret;
47: byte[] data = new byte[len];
48: System.arraycopy(temp, 0, data, 0, len);
49: verboseLog("UDP read", data);
50: return data;
51: }
52:
53: static byte[] sendrecv(SocketAddress local, SocketAddress remote,
54: byte[] data, int max, long endTime) throws IOException {
55: UDPClient client = new UDPClient(endTime);
56: try {
57: if (local != null)
58: client.bind(local);
59: client.connect(remote);
60: client.send(data);
61: return client.recv(max);
62: } finally {
63: client.cleanup();
64: }
65: }
66:
67: static byte[] sendrecv(SocketAddress addr, byte[] data, int max,
68: long endTime) throws IOException {
69: return sendrecv(null, addr, data, max, endTime);
70: }
71:
72: }
|