我正在为我们的组织开发 eclipse 插件。我们通过 eclipse 使用这个插件在用户机器上打开多个服务器[最少 10 个服务器]。对于启动服务器,我们需要尚未绑定的端口号。为此,我使用 serversocket 来检查这一点。我认为打开 serversocket 对象是一项昂贵的操作。在内部 serversocket 将检查端口是否已绑定它至少需要 50 毫秒。这是我返回自由端口的代码。有没有办法在不使用操作系统命令和打开 ServerSocket 的情况下找到已经占用的端口?
/**
*Tries 100 times
* @param port
* modes
* 1.increment - 1
* This mode increment the port with your start value . But it's costly operation because each time we open a socket and check the port is free .
* 2.decrement - 2
* Invert of increment.
* 3.random - 3
* Randomly choose based on your starting point
* @return
*/
public static String getDefaultPort(int port , int mode){
int retry = 100;
int random = 3;
int increment = 1;
int decrement = 2;
while(true){
//this is for preventing stack overflow error.
if(retry < 1){ //retries 100 times .
break;
}
if(mode==increment){
port++;
}else if(mode == decrement){
port--;
}else if(mode == random){
port = (int) (port+Math.floor((Math.random()*1000)));
}
if(validate(port+"")){
long end = System.currentTimeMillis();
return port+"";
}
}
return "";
}
public boolean validate(String input) {
boolean status = true;
try {
int port = Integer.parseInt(input);
ServerSocket ss = new ServerSocket(port);
ss.close();
}
catch (Exception e) {
status = false;
}
return status;
}