编写检测ip端口是否存在的工具类,解决异常ConnectException: failed to connect to /127.0.0.1 (port 12345): connect faile

今天写一个http通信的功能,需求是,灵犀测试工具向灵犀客户端发送http协议的数据,逻辑是当启动灵犀的Activity后,等待3秒就向指定端口发送数据,这里的先等待的原因是:灵犀的10001端口并不是在启动Activity后立即开启,而是过几秒才开启,这里的3秒是我估算的,因此不合适

关于这个异常,我纠结了一晚上,不知道哪出的问题,只好随便写一个端口,当报了同样的错误信息后,我才意识到是因为端口不存在导致的,后来只好做了一个检测端口是否存在的工具类:

	/**
	 * 监测指定地址是否可以连接(重载函数)
	 * @param ip		IP地址
	 * @param port		端口号
	 * @param timeOut	尝试连接的超时时间(单位:毫秒)
	 * @param interval	检测间隔(单位:毫秒)
	 * @author cuixingwang
	 * @date 2014-12-10 上午1:58:05
	 */
	public static boolean checkPort(String ip, int port,long timeOut,long interval){
		long beginTime=System.currentTimeMillis();
		InetSocketAddress inetSocketAddress=new InetSocketAddress(ip,port);
		Socket socket=null;
		while(true){
			try {
				//必须每次都new一个Socket,否则如果第一连接失败,即便之后开启了端口,也不会连接上
				socket = new Socket();
				socket.connect(inetSocketAddress);
				Log.i(TAG,"地址:"+ip+":"+port+"可用");
				//连接成功后先关闭资源,否则再向该端口发数据,速度会非常慢
				socket.close();
				return true;
			} catch (IOException e) {
				Log.e(TAG,"未检测到地址:"+ip+":"+port);
				//注释连接端口失败的异常
				long currentTime=System.currentTimeMillis();
				if(currentTime-beginTime>timeOut){
					//超时则认为连接失败
					return false;
				}
				try {
					Thread.sleep(interval);
				} catch (InterruptedException e2) {
					e2.printStackTrace();
				}
			}
		}
	}


猜你喜欢

转载自blog.csdn.net/razor1991/article/details/41839263
今日推荐