0

我正在编写HTTP WEB SERVER代码。同时,我必须编写有关使用端口的重试策略,以便在该端口服务器上可以侦听客户端的请求。

普通代码:

serversocket = new ServerSocket(ServerSettings.port);

如果ServerSettings.port不是免费的,它会抛出异常。

现在,我想添加重试策略,如果ServerSettings.port不是免费的,请尝试其他端口。为此我写了一段代码,代码如下,

更新代码:

   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");
                }
            }
        }

但是上面的一个显示编码技能很差,而不是专业的。

如何以专业的方式为端口编写重试策略,以便服务器可以侦听该端口?

4

1 回答 1

1

从逻辑上讲,我认为这会起作用(如果有任何语法拼写错误,请纠正我):

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;
     }
}

您可以将它包装在一个函数中,而不是foundPort = true;返回套接字对象。

于 2013-05-06T09:17:38.557 回答