ServerSocket 检测到客户端断开连接

ServerSocket detecting disconnection of client

我正在使用以下代码让我的服务器在连接后继续收听客户端消息。

在收听时,我想检测当 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 没有按预期中断。

我假设当客户端断开连接时会发生这种情况if(read == -1){....}

我刚刚在搜索时发现了这个 post 并且 EJP 的答案给了我关于 read() returns -1 的最佳解决方案,但我才刚刚开始ServerSocket所以我不知道我做的是否正确。

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

如果read为-1,它将抛出异常。我完全希望如此。 只需将该行移动到您的 else 分支,您可以在其中检查 read 是否为 -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 长度 超出范围:)