import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; 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; /** * @name Socket连接异常测试 * @author wujianxiong * @date 2016-5-20 */ public class ConnectTester { public static void main(String[] args){ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String host = "127.0.0.1"; int port = 139; try { String msg = reader.readLine(); //直接敲回车结束循环 while(!msg.isEmpty()&& msg!=null){ String[] strArr = msg.split(" "); host = strArr[0]; port = Integer.parseInt(strArr[1]); //测试连接 ConnectTester.connect(host, port); msg = reader.readLine(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void connect(String host,int port){ SocketAddress remoteAddress = new InetSocketAddress(host, port); Socket socket = new Socket(); try { long beginTime = System.currentTimeMillis(); socket.bind(new InetSocketAddress("10.0.5.128", 80)); socket.connect(remoteAddress, 1000); long endTime = System.currentTimeMillis(); System.out.println(remoteAddress+" take "+(endTime-beginTime)+"ms to connect"); } catch (BindException e) { System.out.println("Local address and port can‘t be binded"); } catch (UnknownHostException e) { // TODO: handle exception System.out.println("UnKnown Host"); } catch (ConnectException e) { System.out.println("Connect Refused"); } catch (SocketTimeoutException e) { System.out.println("Time Out"); } catch (IOException e) { System.out.println("Failed"); } finally{ try { if(socket!=null) socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
原文:http://www.cnblogs.com/nan5-3-105/p/5512892.html