如果你不介意使用的端口,请指定一个0到
ServerSocket constructor的端口,它将在任何空闲端口上侦听。
ServerSocket s = new ServerSocket(0);
System.out.println("listening on port: " + s.getLocalPort());
如果你想使用一组特定的端口,那么最简单的方法是迭代它们直到一个工作。这样的东西:
public ServerSocket create(int[] ports) throws IOException {
for (int port : ports) {
try {
return new ServerSocket(port);
} catch (IOException ex) {
continue; // try next port
}
}
// if the program gets here, no port in the range was found
throw new IOException("no free port found");
}
可以这样使用:
try {
ServerSocket s = create(new int[] { 3843, 4584, 4843 });
System.out.println("listening on port: " + s.getLocalPort());
} catch (IOException ex) {
System.err.println("no available ports");
}