RFC868--时间协议客户机与服务器的实现

本文档详细介绍了基于RFC 868的时间协议的实现,包括客户端和服务器的实现。TimeProtocolConstants类定义了协议的TCP端口和时间差。TimeProtocolClient类实现了获取时间服务器的秒数并将其转换为日期的方法。TimeProtocolServer类创建了一个服务器,监听指定端口,接收并处理客户端请求。提供了测试案例展示如何运行客户端和服务器。
摘要由CSDN通过智能技术生成

 本例根据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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值