I'm writing a Peer-to-Peer Application. I have a default port the application to bind to. But if this fails, I want my application to bind to another open port.
I have a solution for this but I think it's not a very brilliant one.
I'm thinking of something like this:
package de.oompf.netwrk;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
class Server implements Runnable {
private final Thread serverThread;
private final DatagramSocket socket;
Server() throws SocketException {
serverThread = new Thread(this, "Server Thread");
socket = new DatagramSocket(null);
socket.setSoTimeout(2400);
for(int port : Configuration.getPortList()) {
if(!socket.isBound()) {
try {
socket.bind(new InetSocketAddress(port));
break;
} catch(SocketException e) {
}
} else {
break;
}
}
if(!socket.isBound()) {
socket.bind(new InetSocketAddress(0));
}
}
void start() {
serverThread.start();
}
void stop() {
serverThread.interrupt();
socket.close();
}
@Override
public void run() {
DatagramPacket p = new DatagramPacket(new byte[4096], 4096);
while(!serverThread.isInterrupted()) {
try {
socket.receive(p);
} catch (IOException e) {
if(socket.isClosed()) {
break;
}
}
}
}
}
But the socket gets closed after the first unsuccessful try to bind it to a port.
So what's the most elegant way to do this in Java?