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