时间

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

374
使用DatagramChannel的时间服务客户端

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.ByteOrder;/** n  o  w  j  a  v  a . c o m 提 供 **/

import java.nio.channels.DatagramChannel;

import java.util.Iterator;

import java.util.LinkedList;

import java.util.List;


public class Main {

  protected int port = 9999;

  protected List remoteHosts;

  protected DatagramChannel channel;


  public Main() throws Exception {

    this.channel = DatagramChannel.open();

  }

  protected InetSocketAddress receivePacket(DatagramChannel channel,/* 来自 时   代    Java - nowjava.com*/

      ByteBuffer buffer) throws Exception {

    buffer.clear();

    return ((InetSocketAddress) channel.receive(buffer));

  }

  protected void sendRequests() throws Exception {

    ByteBuffer buffer = ByteBuffer.allocate(1);

    Iterator it = remoteHosts.iterator();

    while (it.hasNext()) {

      InetSocketAddress sa = (InetSocketAddress) it.next();

      buffer.clear().flip();

      channel.send(buffer, sa);

    }

  }

  public void getReplies() throws Exception {

    ByteBuffer longBuffer = ByteBuffer.allocate(8);

    longBuffer.order(ByteOrder.BIG_ENDIAN);

    longBuffer.putLong(0, 0);

    longBuffer.position(4);


    ByteBuffer buffer = longBuffer.slice();

    int expect = remoteHosts.size();

    int replies = 0;


    System.out.println("Waiting for replies...");

    while (true) {

      InetSocketAddress sa;

      sa = receivePacket(channel, buffer);

      buffer.flip();

      replies++;

      printTime(longBuffer.getLong(0), sa);

      if (replies == expect) {

        System.out.println("All packets answered");

        break;

      }

      System.out.println("Received " + replies + " of " + expect + " replies");

    }

  }

  protected void printTime(long remote1900, InetSocketAddress sa) {

    System.out.println("Reply from " + sa.getHostName() + ":" + sa.getPort());

  }


  protected 
展开阅读全文