How can I keep trying to obtain a Java DatagramSocket within a thread?
<p>I am working on a Java UDP application. There is a thread in the application whose only job is to listen to a server on a specific port.</p>

<p>I wrote the application under the mistaken assumption that the server I am listening to will always be up; this, however, was a bad assumption.</p>

<p>If my application starts after the server is running, then everything works fine. If my application starts before the server is up, or if the server is restarted while my application is running, my application breaks.</p>

<p><strong>MainClass.java</strong></p>

<pre><code>public class MainClass {
    public static void main(String[] args){
        ListeningClass myListeningClass = new ListeningClass();
        Thread listenerThread = new Thread(myListeningClass);
        listenerThread.setName("My Listening Thread");
        listenerThread.start();
    }
}
</code></pre>

<p><strong>ListeningClass.java</strong></p>

<pre><code>public class ListeningClass implements Runnable {
    private volatile boolean run = true;
    private byte[] receiveBuffer;
    private int receiveBufferSize;
    private DatagramSocket myDatagramSocket;
    private DatagramPacket myDatagramPacket;

    @Override
    public void run(){
        try {
            myDatagramSocket = new DatagramSocket(null);
            InetSocketAddress myInetSocketAddress = new InetSocketAddress(15347);
            myDatagramSocket.bind(myInetSocketAddress);

            receiveBuffer = new byte[2047];
            myDatagramPacket = new DatagramPacket(receiveBuffer, 2047);

            while(run){
                myDatagramSocket.receive(myDatagramPacket);
                byte[] data = myDatagramPacket.getData();
                receiveBufferSize = myDatagramPacket.getLength();
                // process the data received here
            }
        } catch (SocketException se){
            // do stuff
        } catch (IOException ioe){
            // do stuff
        }
    }

    public boolean isRun(){
        return run;
    }

    public void setRun(boolean run){
        this.run = run;
    }
}
</code></pre>

<p>Like I said, if my application starts after the server is running, everything works perfectly, just as expected. However, if my application starts before the server is running, then nothing works. Obviously, is is because the thread tries to open the connection once, and if it fails, then it never tries again.</p>

<p>I moved the DatagramSocket open code to within the while block but that wasn't pretty. I got a bunch of "port already bound" errors.</p>

<p>So, how can I reconstruct this so that it works properly?</p>