2016-03-13 32 views
2

我有一個Java服務器/客戶端應用程序,允許客戶端輸入,直到斷開連接,使用while循環。這是在ClientHandler類對象內部完成的,該對象擴展了Thread並使用run()方法,因此每個連接的客戶端都使用它自己的線程進行通信。Java - 在哪裏檢測並捕獲SocketException

這是迄今爲止發生的事情:

public void run() 
{ 
    //receive and respond to client input 
    try 
    { 
     //strings to handle input from user 
     String received, code, message; 

     //get current system date and time 
     //to be checked against item deadlines 
     Calendar now = Calendar.getInstance(); 

     //get initial input from client 
     received = input.nextLine();     

     //as long as last item deadline has not been reached 
     while (now.before(getLastDeadline())) 
     { 
      ////////////////////////////////// 
      ///processing of client message/// 
      ////////////////////////////////// 

      //reload current system time and repeat loop 
      now = Calendar.getInstance(); 

      //get next input from connected client 
      received = input.nextLine(); 
      //run loop again 
     } 
    } 
    //client disconnects with no further input 
    //no more input detected 
    catch (NoSuchElementException nseEx) 
    { 
     //output to server console 
     System.out.println("Connection to bidder has been lost!"); 
     //no system exit, still allow new client connection 
    } 
} 

這一切工作正常,並且當客戶端停止運行他們的程序NoSuchElementException的處理(因爲不會有後續的輸入)。

我想要做的是檢測客戶端套接字何時與服務器斷開連接,以便服務器可以更新當前連接的客戶端的顯示。我被告知通過捕獲SocketException來做到這一點,並且我已經閱讀了這個異常,但我仍然有點困惑,我將不得不實施它。

根據我的理解(雖然我可能是錯的),SocketException必須在客戶端捕獲。它是否正確?如果是這種情況,那麼SocketException可以與我已有的NoSuchElementException一致運行,還是必須刪除/替換該異常?

一個基本的例子如何合併捕捉SocketException將是一個巨大的幫助,因爲我沒有能夠找到任何相關的例子在線。

感謝,

馬克

回答

1

您已經捕捉SocketException實際。 nextLine呼叫將(最終)在由Socket返回的底層SocketInputStream上呼叫read()。此電話read()將拋出SocketException(這是IOException的子類)。掃描儀類將捕獲IOException,然後返回NoSuchElementException。所以你不需要做任何事情。

您可以通過調用ScannerioException一旦你抓住了NoSuchElementException訪問,如果你想實際SocketException。另外,如果您試圖跟蹤連接的客戶端列表,則必須在服務器端完成。您可以在客戶端捕獲SocketException,但這會表明服務器已意外斷開連接,這不是您真正想要的。

+0

這真的很有幫助,非常感謝! +1 – marcuthh