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

来源:互联网 发布:大连软件开发 编辑:程序博客网 时间:2024/06/03 19:23

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

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

/** * 监测指定地址是否可以连接(重载函数) * @param ipIP地址 * @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();}}}}


0 0
原创粉丝点击