1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
37 public static final void daytimeTCP(String host) throws IOException
38 {
39 DaytimeTCPClient client = new DaytimeTCPClient();
40
41
42 client.setDefaultTimeout(60000);
43 client.connect(host);
44 System.out.println(client.getTime().trim());
45 client.disconnect();
46 }
47
48 public static final void daytimeUDP(String host) throws IOException
49 {
50 DaytimeUDPClient client = new DaytimeUDPClient();
51
52
53 client.setDefaultTimeout(60000);
54 client.open();
55 System.out.println(client.getTime(
56 InetAddress.getByName(host)).trim());
57 client.close();
58 }
59
60
61 public static final void main(String[] args)
62 {
63
64 if (args.length == 1)
65 {
66 try
67 {
68 daytimeTCP(args[0]);
69 }
70 catch (IOException e)
71 {
72 e.printStackTrace();
73 System.exit(1);
74 }
75 }
76 else if (args.length == 2 && args[0].equals("-udp"))
77 {
78 try
79 {
80 daytimeUDP(args[1]);
81 }
82 catch (IOException e)
83 {
84 e.printStackTrace();
85 System.exit(1);
86 }
87 }
88 else
89 {
90 System.err.println("Usage: daytime [-udp] <hostname>");
91 System.exit(1);
92 }
93
94 }
95
96 }
97