Java实现Socket之TimeClient

Java实现Socket之TimeClient

代码内容

  • time.nist.gov服务器的37号端口得到时间信息,并对时间进行解析后显示出来

代码实现

/* TimeClient.java */
import java.io.*;
import java.net.*;
import java.util.Date;

public class TimeClient {
    public final static long differenceBetweenEpochs = 2208988800L;

    public static void main(String[] args) {
        try {
            /* 设置服务器地址和端口号 */
            InetAddress host = InetAddress.getByName("time.nist.gov");
            int port = 37;
            if (args.length > 0) {
                host  = InetAddress.getByName(args[0]);
            }
            /* 建立Socket连接 */
            Socket s = new Socket(host, port);
            /* 从Socket中读取数据 */
            InputStream raw = s.getInputStream();
            /* 时间转换 */
            long secondsSince1900 = 0;
            for (int i = 0; i < 4; i++) {
                secondsSince1900 = (secondsSince1900 << 8) | raw.read();
            }

            long secondsSince1970 = secondsSince1900 - differenceBetweenEpochs;
            long msSince1970 = secondsSince1970 * 1000;
            Date time = new Date(msSince1970);
            System.out.println("It is " + time);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

运行截图

701997-20160204143927007-632521991.png

转载于:https://www.cnblogs.com/wsine/p/5181593.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值