[英]How to code retry policy for port in server side to listen client request?
我正在編寫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");
}
}
}
但以上一項顯示出較差的編碼技能,而不是專業技能。
如何以專業的方式編寫端口的重試策略,以便服務器可以偵聽該端口?
從邏輯上講,我認為這可以解決問題(如果有語法錯誤,請糾正我):
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;
,您將返回套接字對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.