2017-07-28 111 views
0

我想創建一個10秒後停止的Java服務器程序。現在,我正在使用setSoTimeout方法。一旦時間到期,我發現異常並生成服務器關閉消息。使Java服務器在一定的時間後停止

但這似乎是一種解決方法。有沒有更好的方法來做到這一點?

public class DailyAdviceServer 
{ 
String[] adviceList = {"Take smaller bites", "Go for the tight jeans. No they do NOT make you look fat", 
    "One word: inappropriate", "Just for today, be honest. Tell your boss what you *really* think", 
    "You might want to rethink that haircut"}; 

public void startserver() { 
    try { 
     @SuppressWarnings("resource") 
     ServerSocket serverSock = new ServerSocket(2727); 
     serverSock.setSoTimeout(10000); 
     while (true) 
     { 
      Socket sock = serverSock.accept(); 
      OutputStreamWriter streamwriter = new OutputStreamWriter(sock.getOutputStream()); 
      BufferedWriter writer=new BufferedWriter(streamwriter); 

      String advice = getAdvice(); 
      writer.write(advice); 
      writer.close(); 
     } 


    } catch (SocketTimeoutException ex) 
    { 
     System.out.println("The Server has now shut down."); 
    } 
    catch(IOException ex) 
    { 
     ex.printStackTrace(); 
    } 
} 

private String getAdvice() { 
    int random = (int) (Math.random() * adviceList.length); 
    return adviceList[random]; 
} 

public static void main(String[] args) 
{ 
    DailyAdviceServer server = new DailyAdviceServer(); 
    server.startserver(); 
} 

}

回答

0

您可以創建的ServerSocket後啓動一個定時器,當定時器超時後,你可以關閉它

相關問題