Lingering ServerSocket after close() ?

Hey guys,

Maybe I’m revealing my ignorance again, in these threads about networking, but I encountered this:

I have this ServerSocket, bound to port N.
I call setReuseAddress(false);
I close() it and isClosed() returns true.
I try creating a new ServerSocket binding it to port N.

java.net.BindException: Address already in use

After a while, creating the new ServerSocket succeeds.

OS: CentOS (RedHat thingy)

Working around this with this method…


   private static ServerSocket createServerSocket(int port, int backlog, InetAddress bind) throws IOException
   {
      int maxTries = 10;
      long interval = 250;
      
      for(int i=1; i<=maxTries; i++)
      {
         try
         {
            return new ServerSocket(port, backlog, bind);
         }
         catch(IOException exc)
         {
            if(i==maxTries)
               throw exc;
         }

         try
         {
            Thread.sleep(interval);
         }
         catch(InterruptedException exc)
         {
            // ignore
         }
      }
      
      // impossible to get here
      return null;
   }

that might just be the underlaying OS, no time to investigate atm.

You use setReuseAddress on the second ServerSocket to indicate that you don’t care about lingering connections, and want to use the old address immediately. Setting setReuseAddress on the first ServerSocket has no effect on the second ServerSocket.

  • elias

Hm… that explains it. Thanks!