公司的网络不给力啊!
没办法,只好等待网络正常的时候在查阅一些资料,顺便复习下socket!
public static void main(String[] args) {
/**
* 测试网络互通情况
* <p>
* 1.输入完整域名或者Ip地址,端口号
* 2.如果能连接成功,显示连接消耗的时间
* 3.如果连接失败,输出错误信息
* </p>
*/
String host = "";
int port=80;
Scanner sc = new Scanner(System.in);
boolean flag =true;
while (flag) {
System.out.println("请输入域名");
host=sc.next();
System.out.println("请输入端口");
port=Integer.parseInt(sc.next());
new SocketDemo().connect(host, port);
System.out.println("是否需要继续输入,继续请输入T,不继续请输入F");
if (sc.next().equals("T")) {
continue ;
}else{
System.out.println("谢谢使用本系统!");
break;
}
}
}
public void connect(String host,int port){
SocketAddress remoteAddr=new InetSocketAddress(host,port);
Socket socket = null;
String result="";
try {
long begin=System.currentTimeMillis();
socket = new Socket();
socket.connect(remoteAddr, 10000);
long end = System.currentTimeMillis();
result ="恭喜你连接成功,耗时 "+ (end-begin)+"ms";
} catch (BindException e) {
result="local address and port cant bind";
}catch (UnknownHostException e) {
result="Unknow Host";
}catch (ConnectException e) {
result="Connect Refused";
}catch (SocketTimeoutException e) {
result="TimeOut";
}catch (IOException e) {
result="failure";
}finally{
if (socket!=null)
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(remoteAddr+":"+result);
}