本例根据RFC 868网络时间协议分别建立了时间协议的客户机和服务器。
1.TimeProtocolConstants类提供提供两个常量静态值:TCP_PORT指定协议的标准TCP端口;EPOCH_OFFSET_MILLIS储存1970年1月1日0时0分0秒(JVM纪年起始时间) 与 1900年1月1日0时0分0秒(协议纪年起始时间) 时间差的毫秒数。
2.TimeProtocolClient类为客户端。getSecondsSinceEpoch方法通过BufferedInputStream的read方法获得协议中的四个时间字节,并当前计算协议时间的毫秒数;getDate方法计算JVM获得时间的毫秒数,并将毫秒数转换为当前的日期和时间;
3.TimeProtocolServer类为服务端。在构造函数中首先建立ServerSocket,启动线程后阻塞;在run里面调用ServerSocket的accept方法生成socket,并调用process方法处理socket;process方法利BufferedOutputStream的write方法将协议中的四个时间字节传给客户机。
测试:
1.客户端单独测试:
I:/jdk/bin>java com.wrox.timeprotocol.TimeProtocolClient time-a.nist.gov
Fri Aug 24 17:06:33 CST 2007
2.服务端与客户端一起测试:
I:/jdk/bin>java com.wrox.timeprotocol.TimeProtocolServer
Fri Aug 24 23:33:20 CST 2007: TimeProtocolServer(37): info: Accepting connection
s on TCP port 37...
Fri Aug 24 23:33:51 CST 2007: TimeProtocolServer(37): info: Connection from loca
lhost:2145
I:/jdk/bin>java com.wrox.timeprotocol.TimeProtocolClient localhost 37
Fri Aug 24 23:33:50 CST 2007
//TimeProtocolConstants
package com.wrox.timeprotocol;
import java.util.Calendar;
// Defines constants used by clients and servers implementing
// the time protocol defined in RFC 868.
public class TimeProtocolConstants
{
// Prevent instantiation
private TimeProtocolConstants() {}
// The time protocol TCP port defined in RFC 868
public static final int TCP_PORT = 37;
// The number of milliseconds between the RFC 868 epoch,
// January 1st 1900, 0:0:0 UTC, and the Java epoch, January
// 1st 1970, 0:0:0 UTC
public static final long EPOCH_OFFSET_MILLIS;
// Computes the epoch offset
static
{
Calendar calendar = Calendar.getInstance(java.util.TimeZone.getTimeZone("UTC"));
calendar.set(1900, Calendar.JANUARY, 1, 0, 0, 0);
EPOCH_OFFSET_MILLIS = Math.abs(calendar.getTime().getTime());
}
}
//TimeProtocolClient
package com.wrox.timeprotocol;
import java.io.*;
import java.net.*;
import java.util.*;
// Static methods for quering time servers using the RFC-868.
public class TimeProtocolClient
{
// Prevent instantiation
private TimeProtocolClient() {}
// Returns the no. of seconds since Jan 1, 1900 00:00:00 UTC
// obtained by the time server on the given address and port.
/**
* @param address - the address of the time server
* @param port - the port of the time server
*
* @exception IOException - if a com