我有一個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 – marcuthh