package com.chenyang.nse.bussiness.tools.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Random;

public class SocketTool {
   public static boolean isExistPort(String ip, int port) {
      boolean isExistPort = true;
      Socket socket = new Socket();

      try {
         socket.connect(new InetSocketAddress(ip, port));
      } catch (IOException var13) {
         isExistPort = false;
      } finally {
         try {
            socket.close();
         } catch (IOException var12) {
         }

      }

      return isExistPort;
   }

   public static int generatePort(int min, int max) {
      return (new Random()).nextInt(max - min) + min;
   }

   public static Process startRmi(Process process, String command) {
      try {
         process = Runtime.getRuntime().exec(command);
      } catch (IOException e) {
         e.printStackTrace();
      }

      return process;
   }

   public static void closeRmi(Process process) {
      process.destroy();
   }

   public static int getPort() {
      int port = generatePort(6000, 7000);

      for(boolean isExistPort = isExistPort("127.0.0.1", port); isExistPort; isExistPort = isExistPort("127.0.0.1", port)) {
         port = generatePort(6000, 7000);
      }

      System.out.println("端口:" + port);
      return port;
   }

   public static Process start(Process process, int port, String task_realname) {
      boolean isExistPort = false;
      String command = "java -jar /data/hdfs/hdfs.jar " + port + " " + task_realname;
      process = startRmi(process, command);
      isExistPort = isExistPort("127.0.0.1", port);

      while(!isExistPort) {
         isExistPort = isExistPort("127.0.0.1", port);

         try {
            Thread.sleep(100L);
         } catch (InterruptedException var6) {
         }
      }

      return process;
   }

   public static void removeTaskProcess(String taskId) {
      Process process = null;
      String command = "ps -ef |grep " + taskId + " |grep -v 'grep'|awk '{print $2}' | xargs kill -9";

      try {
         process = Runtime.getRuntime().exec(command);
         process.destroy();
      } catch (IOException e) {
         e.printStackTrace();
      }

   }

   public static void main(String[] args) throws Exception {
   }
}
