codeninja.net

my projects
my personal site



CSH
vim powered


Get Firefox
Get Vim
GeoURL

This is a simple client for the Daytime protocol. It is also a simple demonstration of doing UDP socket communication in Java.

Here is the Source Code.
©2000, Sean Graham. License Information

import java.net.*;
import java.io .*;
import java.util.*;

/**
 * The Daytime application connects to a UDP Daytime daemon as a client.  
 *
 * @version 1.0
 * @author Sean M. Graham <grahams {of} csh [dot] rit [dot] educational>
 *
 */
public class Daytime {

    /**
     * This is a simple app, so it only really requires a main().
     *
     * @param   args    The command line arguments
     */
    public static void main(String args[]) {
        if( args.length > 1) {
            System.out.println("Daytime: Too Many Arguments" );
            System.exit(-1);
        }
        try {
            DatagramSocket sock = new DatagramSocket();
            DatagramPacket pak;
            byte msg[] = new byte[64];
            InetAddress daytimeHost = InetAddress.getByName( args[0] );

            // create a datagram packet to send and recieve the reply.  the
            // contents on send don't really matter for this application
            pak = new DatagramPacket( msg, 64, daytimeHost, 13 );

            // Send and receive, and time out after 30 seconds.
            sock.send(pak);
            sock.setSoTimeout(30000);
            sock.receive(pak);

            String received = new String( pak.getData() );
            received = received.trim();

            System.out.println( "Time: " + received );
            
            // Close our socket
            sock.close();
        }
        catch( UnknownHostException e) {
            System.out.println( "Daytime: Invalid Machine Name (" + 
                                 args[0] + ")" );
        }
        catch (InterruptedIOException e) {
            System.out.println("Daytime: Timeout");
        }
        catch (Exception e) {}
    }
}