Java日间客户端

时间:2013-12-09 13:54:05

标签: java

我需要使用以下代码从日期时间服务器获取当前时间。

import java.io.*;
import java.net.*; 

class DaytimeClient {
      public static void main (String[] args) throws IOException {
        if ((args.length != 1))
        ("Syntax: DaytimeClient <host>[:<port>]");

        int idx = args[0].indexOf (":");
        int port = (idx > -1) ? Integer.parseInt (args[0].substring (idx + 1))
          : 13;
        String hostName = (idx > -1) ? args[0].substring (0, idx) : args[0];
        InetAddress host = InetAddress.getByName (hostName);

        DatagramSocket socket = new DatagramSocket ();
        socket.setSoTimeout (5000);
        DatagramPacket packet = new DatagramPacket (new byte[256], 1, host, port);
        socket.send (packet);
        packet.setLength (packet.getData ().length);
        socket.receive (packet);
        socket.close ();

        byte[] data = packet.getData ();
        int length = packet.getLength ();
        System.out.println (new String (data, 0, length, "latin1"));
    }
}

编译后我用“java DaytimeClient 165.193.126.229”运行此代码。但它不起作用。 得到错误

  

C:\ daytimeclient&gt; java DaytimeClient 96.47.67.105   线程“main”中的异常java.net.SocketTimeoutException:接收超时           at java.net.DualStackPlainDatagramSocketImpl.socketReceiveOrPeekData(Native Method)           at java.net.DualStackPlainDatagramSocketImpl.receive0(Unknown Source)           at java.net.AbstractPlainDatagramSocketImpl.receive(Unknown Source)           at java.net.DatagramSocket.receive(Unknown Source)           在DaytimeClient.main(DaytimeClient.java:32)

然后我写了一个服务器,如下,

import java.io.*;
import java.net.*;

public class DaytimeServer {
  public static final int DEFAULT_PORT = 13;
  public static void main (String[] args) throws IOException {
    if (args.length > 1)
      throw new IllegalArgumentException ("Syntax: DaytimeServer [<port>]");
    DatagramSocket socket = new DatagramSocket
      (args.length == 0 ? DEFAULT_PORT : Integer.parseInt (args[0]));
    DatagramPacket packet = new DatagramPacket (new byte[1], 1);
    while (true) {
      socket.receive (packet);
      System.out.println
        ("Received from: " + packet.getAddress () + ":" + packet.getPort ());
      byte[] outBuffer = new java.util.Date ().toString ()
        .getBytes ("latin1");
      packet.setData (outBuffer);
      packet.setLength (outBuffer.length);
      socket.send (packet);
    }
  }
}

使用“java DaytimeClient localhost”运行第一个代码。然后它的工作。

我需要使用remort日间服务器来完成我的工作,所以为什么“java DaytimeClient 165.193.126.229”不起作用。

(参考代码来自http://www.stepwise.hk/npwiki/Tutorial/JavaUDPDaytime

0 个答案:

没有答案