1、代码
package com.socket;
import java.io.IOException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
public class SoketDemo {
public static void main(String[] args) {
String[] a = new String[2];
a[0] = "www.javathinker.org";
a[1] = "80";
String host = "localhost";
int port = 25;
if (a[0].length() > 0) {
host = a[0];
port = Integer.parseInt(a[1]);
}
new SoketDemo().conncet(host, port);
}
public void conncet(String host, int port) {
SocketAddress remoterAddr = new InetSocketAddress(host, port);
Socket socket = null;
String result = null;
try {
long begin = System.currentTimeMillis();
socket = new Socket();
socket.connect(remoterAddr, 1000);// 超时设置时间
long end = System.currentTimeMillis();
result = (end - begin) + "ms";
}
catch (BindException e) {
result = "local address and port can't be binded";
} catch (UnknownHostException e) {
result = "Unknown exception";
} catch (ConnectException e) {
result = "Connection Exception";
} 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(remoterAddr + ":" + result);
}
}
package com.socket;
import java.io.IOException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
public class SoketDemo {
public static void main(String[] args) {
String[] a = new String[2];
a[0] = "www.javathinker.org";
a[1] = "80";
String host = "localhost";
int port = 25;
if (a[0].length() > 0) {
host = a[0];
port = Integer.parseInt(a[1]);
}
new SoketDemo().conncet(host, port);
}
public void conncet(String host, int port) {
SocketAddress remoterAddr = new InetSocketAddress(host, port);
Socket socket = null;
String result = null;
try {
long begin = System.currentTimeMillis();
socket = new Socket();
socket.connect(remoterAddr, 1000);// 超时设置时间
long end = System.currentTimeMillis();
result = (end - begin) + "ms";
}
catch (BindException e) {
result = "local address and port can't be binded";
} catch (UnknownHostException e) {
result = "Unknown exception";
} catch (ConnectException e) {
result = "Connection Exception";
} 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(remoterAddr + ":" + result);
}
}
}
2、输出结果截图