2016-10-19 109 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长度范围:)

相关问题