私たちの組織のためにEclipseプラグインを開発しています。eclipse 経由でこのプラグインを使用して、ユーザー マシン上で複数のサーバー [最小 10 サーバー] を開いています。サーバーを起動するには、まだバインドされていないポート番号が必要です。そのために、serversocket を使用してこれを確認しています。サーバーソケットオブジェクトを開くのはコストのかかる操作だと思います。内部的に、serversocket は、ポートが既にバインドされているかどうかを確認します。これには、少なくとも 50 ミリ秒かかります。空きポートを返すコードは次のとおりです。OS コマンドを使用して 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;
}