集册 Java实例教程 DatagramChannel时间服务器,提供RFC 868时间服务(http://www.ietf.org/RFC/rfc0868.txt)

DatagramChannel时间服务器,提供RFC 868时间服务(http://www.ietf.org/RFC/rfc0868.txt)

欢马劈雪     最近更新时间:2020-01-02 10:19:05

121
DatagramChannel时间服务器,提供RFC 868时间服务(http://www.ietf.org/RFC/rfc0868.txt)

import java.net.InetSocketAddress;

import java.net.SocketAddress;

import java.net.SocketException;/*时 代 J a v a 提 供*/

import java.nio.ByteBuffer;

import java.nio.ByteOrder;

import java.nio.channels.DatagramChannel;


public class Main {

  private static final int DEFAULT_TIME_PORT = 9999;

  private static final long DIFF_1900 = 2208988800L;


  protected DatagramChannel channel;


  public Main() throws Exception {

    this.channel = DatagramChannel.open();

    this.channel.socket().bind(new InetSocketAddress(DEFAULT_TIME_PORT));

    System.out.println("Listening on port " + DEFAULT_TIME_PORT+ " for time requests");

  }

  public void listen() throws Exception {

    ByteBuffer longBuffer = ByteBuffer.allocate(8);
    /*
    时   代    Java - nowjava.com 提供
    */

    longBuffer.order(ByteOrder.BIG_ENDIAN);

    longBuffer.putLong(0, 0);

    longBuffer.position(4);

    ByteBuffer buffer = longBuffer.slice();

    while (true) {

      buffer.clear();

      SocketAddress sa = this.channel.receive(buffer);

      if (sa == null) {

        continue;

      }

      System.out.println("Time request from " + sa);

      buffer.clear();

      longBuffer.putLong(0, (System.currentTimeMillis() / 1000) + DIFF_1900);


      this.channel.send(buffer, sa);

    
展开阅读全文