我正在编写 HTTP WEB SERVER 代码。同时我必须使用端口编写重试策略,以便在该端口服务器上可以监听客户端的请求。
普通代码:
serversocket = new ServerSocket(ServerSettings.port);
如果ServerSettings.port
不是免费的话,它会抛出异常。
现在,我想添加重试策略,如果ServerSettings.port
不可用,请尝试其他端口。为此,我写了一个代码,代码是一个s,
更新代码:
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");
}
}
}
但是上面显示的是编码技巧不佳,而不是专业编码技能。
如何以专业的方式为端口编写重试策略,以便服务器可以侦听该端口?
答案 0 :(得分: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;
,你将返回套接字对象。