java获取系统时间,使用UDP
如果对方服务器开启了 daytime 服务,直接连接到对方的 13 端口。
如果是 TCP 连接上后,对方立即会答复,你不需要开口。
如果是 UDP 你发送任何东西(比如长度为1的字节),对方只要收到你数据包立即就会回复。
String hostName = "localhost";
int port = 13;
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"));
int port = 13;
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"));
是要用UDP获取远程主机的时间吗?
是获取本机时间 然后用数据包把它传送到本机 谢谢
123