我使用以下代码让我的服务器在连接后继续收听客户端消息。
在收听时,我想检测当return $this->hasMany(Questions::class, 'people_id', 'id');
值变为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=-1
未按预期完成。
我假设当客户端断开连接时,会出现WhileLoop
这种情况。
我在搜索时发现了这个post, EJP 的答案给了我if(read == -1){....}
的最佳解决方案,但我刚刚开始{{1}所以我不知道我是否正确地做到了。
答案 0 :(得分: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-
抛出: IndexOutOfBoundsException - 如果offset和length参数索引字节数组边界之外的字符
-1长度 超出界限:)