【问题标题】:How to code retry policy for port in server side to listen client request?如何编写服务器端端口的重试策略以侦听客户端请求?
【发布时间】:2013-05-06 08:52:20
【问题描述】:

我正在编写 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");
                }
            }
        }

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

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

【问题讨论】:

  • 也许将其包装在while-loop 中,检查boolean 类型变量,以判断端口是否空闲?对象创建后:portIsFree = true,重试条件为portIsFree == false
  • @GuyDavid 检查端口是否空闲的方法是什么?
  • ServerSocket 如果未能使用给定的端口,将抛出异常,因此之后不会执行任何代码——它将通过设置portIsFree = true; 的行,并跳转到@ 987654331@部分。循环将继续,因为portIsFree 仍设置为false
  • 如果第一个端口失败,客户端如何知道服务器正在使用的其他端口?在您决定之前,担心如何编写服务器端是没有意义的。很可能你根本不应该有一个“重试策略”:只为服务器保留端口,如果它不可用,退出并让操作员处理它。

标签: java algorithm sockets http


【解决方案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;,您将返回套接字对象。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-01-16
  • 2019-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-03
  • 1970-01-01
  • 2021-02-04
相关资源
最近更新 更多