If you don't mind the port used, specify a port of 0 to the ServerSocket constructor and it will listen on any free port.
ServerSocket s = new ServerSocket(0);
System.out.println("listening on port: " + s.getLocalPort());
If you want to use a specific set of ports, then the easiest way is probably to iterate through them until one works. Something like this:
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");
}
Could be used like so:
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");
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…