package Chapter2;
import java.io.IOException; import java.net.*;
public class ConnectTester { public static void main(String[] args) { String host = "localhost"; int port = 8000; if (args.length > 1) { host=args[0]; port = Integer.parseInt(args[1]); } new ConnectTester().connect(host, port); }
public void connect(String host, int port) { // SocketAddress remoteAdd = new InetSocketAddress(host, port); Socket socket = null; String result = ""; try { long begin = System.currentTimeMillis(); socket = new Socket(); socket.connect(remoteAdd, 10000);//最长连接用时为10秒 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 Host"; } catch (ConnectException e) { result = "ConnectException"; } catch (SocketTimeoutException e) { result = "TimeOut"; } catch (IOException e) { result = "failure"; } finally { try { if (socket != null) socket.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("访问:"+socket.getRemoteSocketAddress()+"连接用时" + result);
}
}
转载于:https://www.cnblogs.com/stay-sober/p/4158794.html
相关资源:数据结构—成绩单生成器