01: /*
02: * Copyright 2001-2005 The Apache Software Foundation
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.apache.commons.net;
17:
18: import java.io.IOException;
19: import java.net.DatagramPacket;
20: import java.net.InetAddress;
21:
22: /***
23: * The DaytimeUDPClient class is a UDP implementation of a client for the
24: * Daytime protocol described in RFC 867. To use the class, merely
25: * open a local datagram socket with
26: * {@link org.apache.commons.net.DatagramSocketClient#open open }
27: * and call {@link #getTime getTime } to retrieve the daytime
28: * string, then
29: * call {@link org.apache.commons.net.DatagramSocketClient#close close }
30: * to close the connection properly. Unlike
31: * {@link org.apache.commons.net.DaytimeTCPClient},
32: * successive calls to {@link #getTime getTime } are permitted
33: * without re-establishing a connection. That is because UDP is a
34: * connectionless protocol and the Daytime protocol is stateless.
35: * <p>
36: * <p>
37: * @author Daniel F. Savarese
38: * @see DaytimeTCPClient
39: ***/
40:
41: public final class DaytimeUDPClient extends DatagramSocketClient {
42: /*** The default daytime port. It is set to 13 according to RFC 867. ***/
43: public static final int DEFAULT_PORT = 13;
44:
45: private byte[] __dummyData = new byte[1];
46: // Received dates should be less than 256 bytes
47: private byte[] __timeData = new byte[256];
48:
49: /***
50: * Retrieves the time string from the specified server and port and
51: * returns it.
52: * <p>
53: * @param host The address of the server.
54: * @param port The port of the service.
55: * @return The time string.
56: * @exception IOException If an error occurs while retrieving the time.
57: ***/
58: public String getTime(InetAddress host, int port)
59: throws IOException {
60: DatagramPacket sendPacket, receivePacket;
61:
62: sendPacket = new DatagramPacket(__dummyData,
63: __dummyData.length, host, port);
64: receivePacket = new DatagramPacket(__timeData,
65: __timeData.length);
66:
67: _socket_.send(sendPacket);
68: _socket_.receive(receivePacket);
69:
70: return new String(receivePacket.getData(), 0, receivePacket
71: .getLength());
72: }
73:
74: /*** Same as <code>getTime(host, DaytimeUDPClient.DEFAULT_PORT);</code> ***/
75: public String getTime(InetAddress host) throws IOException {
76: return getTime(host, DEFAULT_PORT);
77: }
78:
79: }
|