2016-10-19 111 views
1

我使用下面的代碼讓我的服務器在連接時繼續偵聽客戶端消息。ServerSocket檢測到客戶端斷開連接

在收聽時,我想要檢測當read值變爲-1並完成WhileLoop時客戶端是否斷開連接。

private volatile boolean isConnected = true; 
//.... 
while(isConnected){ //Whe it comes to false then Receiving Message is Done. 
    try { 
     socket.setSoTimeout(10000); //Timeout is 10 Seconds 
     InputStream inputStream = socket.getInputStream(); 
     BufferedInputStream inputS = new BufferedInputStream(inputStream); 
     byte[] buffer = new byte[256]; 
     int read = inputS.read(buffer); 
     String msgData = new String(buffer,0,read); 

     //Detect here when client become disconnected 
     if(read == -1){ //Client become disconnected 
      isConnected = false; 
      Log.w(TAG,"Client is no longer Connected!"); 
     }else{ 
      isConnected = true; 
      Log.w(TAG,"Client Still Connected..."); 
     } 

     //.... 
    }catch (SocketException e) { 
     Log.e(TAG,"Failed to Receive message from Client, SocketException occured => " + e.toString()); 
    }catch (IOException e) { 
     Log.e(TAG,"Failed to Receive message from Client, IOException occured => " + e.toString()); 
    }catch (Exception e) { 
     Log.e(TAG,"Failed to Receive message from Client, Exception occured => " + e.toString()); 
    }   
} 

Log.w(TAG, "Receiving Message is Done."); 

上述代碼適用於接收消息,但我在客戶端斷開連接時遇到問題。

當客戶端斷開連接時,會發生異常,並出現以下錯誤:java.lang.StringIndexOutOfBoundsException: length=256; regionStart=0; regionLength=-1WhileLoop未按預期完成。

我假設當客戶端斷開連接時,這種情況將發生if(read == -1){....}

我剛剛發現這個post而搜索和EJP答案給我最好的解決辦法上read() returns -1,但我剛開始在ServerSocket所以我不知道如果我做正確。

+2

之外,如果讀回報你不應該構建字符串-1。如果'if(read == -1)',我會簡單地將字符串結構移動到else分支。 – Fildor

+0

@Fildor - 跆拳道,大聲笑,是我剛做錯了什麼?我試過了,客人是什麼?有用!!! – lopi

+0

@Fildor - 如何做出答案而不是評論?我很高興地將這個標記作爲一個正確的答案。 :-) – lopi

回答

2

String msgData = new String(buffer,0,read);

如果read爲-1,它會拋出異常。我完全期待這一點。 只需將該行移動到else分支,在該分支中檢查是否讀取-1,以便僅在實際存在數據時才構造字符串。

參見:https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#String-byte:A-int-int-

Throws: IndexOutOfBoundsException - If the offset and the length arguments index characters outside the bounds of the bytes array

-1長度範圍:)

相關問題