初学网络编程,怎么才能获得时间。服务器名填tock.usno.navy.mil提示找不到服务器,如果填time.windows.com或者其他的提示Connection refused
import java.io.*;
import java.net.*;
public class SimpleDaytimeClient { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String sHostName;
/*
* Get the name of the server from the command line. No entry,use
* tock.usno.navy.mil
*/
if(args.length>0){
sHostName = args[0];
}
else{
sHostName = "tock.usno.navy.mil";
}
/*
* Opeb a socket to port 13. Prepare to receive the Daytime information.
*/
try{
Socket oSocket = new Socket(sHostName,13);
InputStream oTimeStream =oSocket.getInputStream();
StringBuffer oTime = new StringBuffer();
// Fetch the Daytime information.
int iCharacter;
while((iCharacter = oTimeStream.read()) != -1){
oTime.append((char)iCharacter);
}
// Convert Daytime to a String and output.
String sTime = oTime.toString().trim();
System.out.println("It's" + sTime + "at" + sHostName + ".");
oTimeStream.close();
oSocket.close();
}catch (UnknownHostException e){
System.err.print(e);
}catch (IOException e){
System.err.print(e);
}
}
}
import java.io.*;
import java.net.*;
public class SimpleDaytimeClient { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String sHostName;
/*
* Get the name of the server from the command line. No entry,use
* tock.usno.navy.mil
*/
if(args.length>0){
sHostName = args[0];
}
else{
sHostName = "tock.usno.navy.mil";
}
/*
* Opeb a socket to port 13. Prepare to receive the Daytime information.
*/
try{
Socket oSocket = new Socket(sHostName,13);
InputStream oTimeStream =oSocket.getInputStream();
StringBuffer oTime = new StringBuffer();
// Fetch the Daytime information.
int iCharacter;
while((iCharacter = oTimeStream.read()) != -1){
oTime.append((char)iCharacter);
}
// Convert Daytime to a String and output.
String sTime = oTime.toString().trim();
System.out.println("It's" + sTime + "at" + sHostName + ".");
oTimeStream.close();
oSocket.close();
}catch (UnknownHostException e){
System.err.print(e);
}catch (IOException e){
System.err.print(e);
}
}
}
我试了其他的比如:
www.time.ac.cn为中科院国家授时中心,采用北京时间
time.nist.gov为美国标准技术院,采用格灵威时间
就提示Connection refused好像端口固定的是13
如假如你装了Tomcat,则主机为:"127.0.0.1"或"localhos",而端口为:8080啊
我测试了,程序在"iCharacter = oTimeStream.read()"这里阻塞了
我分析应该是:服务器没有向你的机子写数据,所以程序在那阻塞了,不往下执行了 但是,从上面可以分析的出:连接到服务器是没问题的。
如果你出现Connection refused,看是否你上了网连接到那服务器
基于TCP的daytime服务
daytime服务是基于TCP的应用,服务器在TCP端口13侦听,一旦有连接建立就返回ASCII形式的日期和时间,在传送完后关闭连接。接收到的数据被忽略。
基于UDP的daytime服务
daytime服务也可以使用UDP协议,它的端口也是13,不过UDP是用数据报传送当前时间的。接收到的数据被忽略。
现在我只需要找到一个实现了DAYTIME协议的服务器,并连接服务器就应该能接收到时间吧?