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 examples;
17:
18: import java.io.IOException;
19: import java.net.InetAddress;
20: import org.apache.commons.net.DaytimeTCPClient;
21: import org.apache.commons.net.DaytimeUDPClient;
22:
23: /***
24: * This is an example program demonstrating how to use the DaytimeTCP
25: * and DaytimeUDP classes.
26: * This program connects to the default daytime service port of a
27: * specified server, retrieves the daytime, and prints it to standard output.
28: * The default is to use the TCP port. Use the -udp flag to use the UDP
29: * port.
30: * <p>
31: * Usage: daytime [-udp] <hostname>
32: * <p>
33: ***/
34: public final class daytime {
35:
36: public static final void daytimeTCP(String host) throws IOException {
37: DaytimeTCPClient client = new DaytimeTCPClient();
38:
39: // We want to timeout if a response takes longer than 60 seconds
40: client.setDefaultTimeout(60000);
41: client.connect(host);
42: System.out.println(client.getTime().trim());
43: client.disconnect();
44: }
45:
46: public static final void daytimeUDP(String host) throws IOException {
47: DaytimeUDPClient client = new DaytimeUDPClient();
48:
49: // We want to timeout if a response takes longer than 60 seconds
50: client.setDefaultTimeout(60000);
51: client.open();
52: System.out.println(client.getTime(InetAddress.getByName(host))
53: .trim());
54: client.close();
55: }
56:
57: public static final void main(String[] args) {
58:
59: if (args.length == 1) {
60: try {
61: daytimeTCP(args[0]);
62: } catch (IOException e) {
63: e.printStackTrace();
64: System.exit(1);
65: }
66: } else if (args.length == 2 && args[0].equals("-udp")) {
67: try {
68: daytimeUDP(args[1]);
69: } catch (IOException e) {
70: e.printStackTrace();
71: System.exit(1);
72: }
73: } else {
74: System.err.println("Usage: daytime [-udp] <hostname>");
75: System.exit(1);
76: }
77:
78: }
79:
80: }
|