Java TCP 和UDP Time 协议服务器和客户端

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);
	}
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值