001 /* 002 * Copyright 2001-2005 The Apache Software Foundation 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 package examples; 017 018 import java.io.IOException; 019 import java.net.InetAddress; 020 import org.apache.commons.net.DaytimeTCPClient; 021 import org.apache.commons.net.DaytimeUDPClient; 022 023 /*** 024 * This is an example program demonstrating how to use the DaytimeTCP 025 * and DaytimeUDP classes. 026 * This program connects to the default daytime service port of a 027 * specified server, retrieves the daytime, and prints it to standard output. 028 * The default is to use the TCP port. Use the -udp flag to use the UDP 029 * port. 030 * <p> 031 * Usage: daytime [-udp] <hostname> 032 * <p> 033 ***/ 034 public final class daytime 035 { 036 037 public static final void daytimeTCP(String host) throws IOException 038 { 039 DaytimeTCPClient client = new DaytimeTCPClient(); 040 041 // We want to timeout if a response takes longer than 60 seconds 042 client.setDefaultTimeout(60000); 043 client.connect(host); 044 System.out.println(client.getTime().trim()); 045 client.disconnect(); 046 } 047 048 public static final void daytimeUDP(String host) throws IOException 049 { 050 DaytimeUDPClient client = new DaytimeUDPClient(); 051 052 // We want to timeout if a response takes longer than 60 seconds 053 client.setDefaultTimeout(60000); 054 client.open(); 055 System.out.println(client.getTime( 056 InetAddress.getByName(host)).trim()); 057 client.close(); 058 } 059 060 061 public static final void main(String[] args) 062 { 063 064 if (args.length == 1) 065 { 066 try 067 { 068 daytimeTCP(args[0]); 069 } 070 catch (IOException e) 071 { 072 e.printStackTrace(); 073 System.exit(1); 074 } 075 } 076 else if (args.length == 2 && args[0].equals("-udp")) 077 { 078 try 079 { 080 daytimeUDP(args[1]); 081 } 082 catch (IOException e) 083 { 084 e.printStackTrace(); 085 System.exit(1); 086 } 087 } 088 else 089 { 090 System.err.println("Usage: daytime [-udp] <hostname>"); 091 System.exit(1); 092 } 093 094 } 095 096 } 097