2012-01-20 92 views
0

我需要一種方法來自動關閉通過使用某種計時器運行的服務器程序。直到現在這是我得到的如何自動關閉Java服務器?

long start = System.currentTimeMillis(); 
    long end = start + 10 * 1000; // 60 seconds * 1000 ms/sec 

    while (System.currentTimeMillis() < end) { 
     Socket connectionSocket = welcomeSocket.accept(); 
     BufferedReader inFromClient = new BufferedReader(
       new InputStreamReader(connectionSocket.getInputStream())); 
     DataOutputStream outToClient = new DataOutputStream(
       connectionSocket.getOutputStream()); 
     clientSentence = inFromClient.readLine(); 
     System.out.println("Received: " + clientSentence); 
     capitalizedSentence = clientSentence.toUpperCase() + '\n'; 
     outToClient.writeBytes(capitalizedSentence); 
     count = count + 1; 

    } 
    welcomeSocket.close(); 

這可能嗎?請幫忙,不要投票。我很喜歡Java中的客戶端服務器。

回答

1

您可以使用setSoTimeout

通常情況下,您將設置一些值爲100毫秒的值,輸入一個循環並調用accept。當超時異常被拋出時,你會檢查它是否退出或不退出循環或繼續。

然後確保在完成後清理套接字。

0

我不確定你是否可以用Threads。仍然建議你看看Timer課程。

您可以創建一個Timer,它創建了一個關閉服務器的線程。您可以爲final variable您的連接,然後使用synchronised訪問它一旦關閉Timer線程踢英寸

1

運行你有沒有在一個線程(在下面的代碼命名的服務器)的代碼,然後再開始另一個當你想退出時,這樣的線程執行一箇中斷:

Thread server = {the one you have}; 
Thread timeout = new Thread() { 
    public void run() { 
     long end = start + 10 * 1000; 
     try { 
      Thread.sleep(end); 
     } catch (InterruptedException e) { 
      //handle this 
     } 
     server.interrupt(); 
    } 
} 
timeout.start(); 

socket.accept現在將拋出InterruptedException並繞過所有其他代碼。