![](https://i-blog.csdnimg.cn/blog_migrate/6f47ab114b943876819b7c62925888bb.jpeg)
import java.io.*;
import java.net.*;
import java.util.Date;
public class TCPTimeServer {
public final static int PORT = 37;
public static void main(String[] args) {
// The time protocol sets the epoch at 1900,
// the Date class at 1970. This number
// converts between them.
long differenceBetweenEpochs = 2208988800L;
try (ServerSocket server = new ServerSocket(PORT)) {
while (true) {
try (Socket connection = server.accept()) {
OutputStream out = connection.getOutputStream();
Date now = new Date();
long msSince1970 = now.getTime();
long secondsSince1970 = msSince1970/1000;
long secondsSince1900 = secondsSince1970
+ differenceBetweenEpochs;
byte[] time = new byte[4];
time[0]
= (byte) ((secondsSince1900 & 0x00000000FF000000L) >> 24);
time[1]
= (byte) ((secondsSince1900 & 0x0000000000FF0000L) >> 16);
time[2]
= (byte) ((secondsSince1900 & 0x000000000000FF00L) >> 8);
time[3] = (byte) (secondsSince1900 & 0x00000000000000FFL);
out.write(time);
out.flush();
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.Socket;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class TimeProtocolClientTCP {
public static void main(String[] args) throws Exception {
Socket s = new Socket("time.nist.gov", 37);
// long differenceBetweenEpochs = 2208988800L;
// If you'd rather not use the magic number, uncomment
// the following section which calculates it directly.
TimeZone gmt = TimeZone.getTimeZone("GMT");
Calendar epoch1900 = Calendar.getInstance(gmt);
epoch1900.set(1900, 01, 01, 00, 00, 00);
long epoch1900ms = epoch1900.getTime().getTime();
Calendar epoch1970 = Calendar.getInstance(gmt);
epoch1970.set(1970, 01, 01, 00, 00, 00);
long epoch1970ms = epoch1970.getTime().getTime();
long differenceInMS = epoch1970ms - epoch1900ms;
long differenceBetweenEpochs = differenceInMS / 1000;
System.out.println(differenceBetweenEpochs);
try {
InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
// Reads a 32 bit value (4 bytes) in Big-Endian order.
// The unsigned value is the number of seconds elapsed since
// January 1, 1900, 00:00:00 GMT
int t = dis.readInt();
// Converts to milliseconds from "the epoch" (January 1, 1970, 00:00:00 GMT)
long millisFromEpoch = ((t & 0xFFFFFFFFL) - 2208988800L) * 1000L;
System.out.println(new Date(millisFromEpoch));
} finally {
s.close();
}
}
}
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Date;
/**
* Title: MultithreadedUdpDaytimeServer Description: Multithreaded UDP daytime
* server class Author: William Chanrico Date: 7-June-2017
*/
public class UDPTimeServer {
private DatagramSocket socket;
public static void main(String[] args) {
new UDPTimeServer(37);
}
public UDPTimeServer(int port) {
try {
socket = new DatagramSocket(port);
System.out.println("UDP time server is listening on port " + port);
while (true) {
DatagramPacket request = new DatagramPacket(new byte[1024], 1024);
socket.receive(request);
Thread task = new ServerThread(request);
task.start();
}
} catch (SocketException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private class ServerThread extends Thread {
private final DatagramPacket request;
ServerThread(DatagramPacket request) {
this.request = request;
}
@Override
public void run() {
long differenceBetweenEpochs = 2208988800L;
InetAddress cliAddr = request.getAddress();
int cliPort = request.getPort();
try {
Date now = new Date();
long msSince1970 = now.getTime();
long secondsSince1970 = msSince1970 / 1000;
long secondsSince1900 = secondsSince1970 + differenceBetweenEpochs;
byte[] time = new byte[4];
time[0] = (byte) ((secondsSince1900 & 0x00000000FF000000L) >> 24);
time[1] = (byte) ((secondsSince1900 & 0x0000000000FF0000L) >> 16);
time[2] = (byte) ((secondsSince1900 & 0x000000000000FF00L) >> 8);
time[3] = (byte) (secondsSince1900 & 0x00000000000000FFL);
DatagramPacket response = new DatagramPacket(time, time.length, cliAddr, cliPort);
socket.send(response);
System.out.println("Served a client from " + cliAddr + ":" + cliPort);
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.DatagramChannel;
import java.util.Date;
public class TimeProtocolClientUDP {
public static void main(String[] args) throws Exception {
DatagramChannel channel = DatagramChannel.open();
// port 0 selects any available port
SocketAddress address = new InetSocketAddress(0);
DatagramSocket socket = channel.socket();
socket.setSoTimeout(5000);
socket.bind(address);
SocketAddress server = new InetSocketAddress("time.nist.gov", 37);
ByteBuffer buffer = ByteBuffer.allocate(8192);
// time protocol always uses big-endian order
buffer.order(ByteOrder.BIG_ENDIAN);
// Must put at least one byte of data in the buffer;
// it doesn't matter what it is.
buffer.put((byte) 65);
buffer.flip();
channel.send(buffer, server);
buffer.clear();
buffer.put((byte) 0).put((byte) 0).put((byte) 0).put((byte) 0);
channel.receive(buffer);
buffer.flip();
long secondsSince1900 = buffer.getLong();
channel.close();
// Converts to milliseconds from "the epoch" (January 1, 1970, 00:00:00 GMT)
long millisFromEpoch = ((secondsSince1900 & 0xFFFFFFFFL) - 2208988800L) * 1000L;
System.out.println(new Date(millisFromEpoch));
}
}
import java.net.*;
import java.util.*;
public class UDPTimeClient {
public final static int PORT = 37;
public final static String DEFAULT_HOST = "time.nist.gov";
public static void main(String[] args) {
InetAddress host;
try {
if (args.length > 0) {
host = InetAddress.getByName(args[0]);
} else {
host = InetAddress.getByName(DEFAULT_HOST);
}
} catch (RuntimeException | UnknownHostException ex) {
System.out.println("Usage: java UDPTimeClient [host]");
return;
}
UDPPoke poker = new UDPPoke(host, PORT);
byte[] response = poker.poke();
if (response == null) {
System.out.println("No response within allotted time");
return;
} else if (response.length != 4) {
System.out.println("Unrecognized response format");
return;
}
// The time protocol sets the epoch at 1900,
// the Java Date class at 1970. This number
// converts between them.
long differenceBetweenEpochs = 2208988800L;
long secondsSince1900 = 0;
for (int i = 0; i < 4; i++) {
secondsSince1900 = (secondsSince1900 << 8) | (response[i] & 0x000000FF);
}
long secondsSince1970 = secondsSince1900 - differenceBetweenEpochs;
long msSince1970 = secondsSince1970 * 1000;
Date time = new Date(msSince1970);
System.out.println(time);
}
}