UDP Time Client - Java Network

Java examples for Network:URL Download

Description

UDP Time Client

Demo Code



import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.DatagramChannel;
import java.util.Date;

public class UDPTimeClient {

    public static void main(String[] args) throws IOException {
        DatagramChannel channel = DatagramChannel.open();
        DatagramSocket socket = channel.socket();
        socket.setSoTimeout(5000);/*ww w  .  j  av  a2 s.  c o m*/
        InetSocketAddress server = new InetSocketAddress("time.nist.gov",
                37);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.order(ByteOrder.BIG_ENDIAN);

        buffer.clear();
        buffer.put((byte) 65);
        buffer.flip();

        channel.send(buffer, server);

        buffer.clear();
        channel.receive(buffer);
        buffer.flip();

        int size = buffer.capacity();
        byte[] receviedData = new byte[size];
        System.arraycopy(buffer.array(), 0, receviedData, 0, size);

        long differBtw = 2208988800L;
        long secondsSince1900 = 0;
        for (int i = 0; i < 4; i++) {
            secondsSince1900 = (secondsSince1900 << 8)
                    | (receviedData[i] & 0x000000FF);

        }

        long secondsSince1970 = secondsSince1900 - differBtw;
        long msSince1970 = secondsSince1970 * 1000;
        Date time = new Date(msSince1970);
        System.out.println(time);
        channel.close();

    }

}

Related Tutorials