Java determine whether the IP and port number can be accessed

The first grant of the reasons why the project would like to achieve is a need to be able to connect on database early to judge the results online to find a lot of ways basically isReachable are used () judgment, do not know why this method always return False, so only write yourself a a. The following code directly, to a method of first ping IP and port number

 

public boolean isHostConnection(String ip, int port) {
          Socket socket = new Socket();
         try {
              socket.connect(new InetSocketAddress(ip, port),3000);
         } catch (SocketTimeoutException s) {
              return false;
        } catch (IOException e) {
             e.printStackTrace();
            return false;
       } finally {
             try {
                  socket.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
      }
      return true;
}

 

// The following is a return connection state

public List<HashMap<String,Object>> getConnectionState(){
           List<HashMap<String,Object>> listMap = new ArrayList<HashMap<String, Object>>();
           try {
                  List<FactoryDataBaseConfig> fdb = factoryDataBaseConfigService.getFactoryState();
                  List<String> list = new ArrayList<String>();
                  HashMap<String,Object> map = new HashMap<String,Object>();
                 for(int i = 0; i < fdb.size(); i++){
                       boolean result = false;
                       result = this.isHostConnectable(fdb.get(i).getIpHost(), 1433);
                       if(result){
                                  int factoryState = factoryDataBaseConfigService.updateStateTrue(fdb.get(i).getOrgfk());
                                  if(factoryState == 1){
                                                map.put("state", true);
                                  }else{
                                               map.put("state", false);
                                  }
                    }else{
                               int factoryState = factoryDataBaseConfigService.updateStateFalse(fdb.get(i).getOrgfk());
                                    if(factoryState == 1){
                                              map.put("state", true);
                                    }else{
                                              map.put("state", false);
                                    }
                              list.add(fdb.get(i).getOrgname());
                   }
                }
                   map.put("list", list);
                   listMap.add(map);
             } catch (Exception e) {
                       throw new RuntimeException(e.getMessage());
            }
            return listMap;
}

Guess you like

Origin www.cnblogs.com/0000cjw/p/11129115.html