devsda
devsda

Reputation: 4222

How to code retry policy for port in server side to listen client request?

I am writing HTTP WEB SERVER code. In the mean while I have to code retry policy on using port, so that on that port server can listen client's request.

Normal Code:

serversocket = new ServerSocket(ServerSettings.port);

It throws Exception, if ServerSettings.port is not free.

Now, I want to add retry policy, if ServerSettings.port is not free, try other ports. For that I write one code, and code is a s follows,

Updated Code:

   try {
            serversocket = new ServerSocket(ServerSettings.port);
        } catch (IOException io) {
            try {
                ServerSettings.port += 505;
                serversocket = new ServerSocket(ServerSettings.port);
            } catch (IOException io1) {
                try {
                    ServerSettings.port += 505;
                    serversocket = new ServerSocket(ServerSettings.port);
                } catch (IOException io2) {
                    log.info(new Date() + "Problem occurs in binding port");
                }
            }
        }

But above one shows poor coding skills, and not professional one.

How can I write retry policy for ports in a professional way, so that server can listen on that port?

Upvotes: 0

Views: 717

Answers (1)

Novak
Novak

Reputation: 2768

Logically, I think this will work (Correct me if there are any syntax typos):

ServerSocket serversocket; 
boolean foundPort = false;

while (!foundPort)
{
     try {
          serversocket = new ServerSocket(ServerSettings.port); // If this fails, it will jump to the `catch` block, without executing the next line
          foundPort = true;
     }
     catch (IOException io) {
          ServerSettings.port += 505;
     }
}

You could wrap it in a function, and instead of foundPort = true;, you would return the socket object.

Upvotes: 1

Related Questions