这不是我第一次尝试理解这个问题,但我希望这将是最后一个:
一些背景:
我有一个Java SocketChannel NIO
在非阻塞模式下工作的服务器。
该服务器有多个客户端,它们从它发送和接收消息。
"keepalive"
每个客户端每隔一段时间就通过消息保持与服务器的连接。服务器的主要思想是客户端将“一直”保持连接并以“推送”模式接收来自它的消息。
现在我的问题:
在 Java NIOread()
函数中 - 当 read() 返回 -1 - 这意味着它的 EOS。
在我在这里提出的问题中,我意识到这意味着套接字已完成其当前流并且不需要关闭..
当在谷歌搜索更多关于这个时,我发现这确实意味着连接在另一边关闭..
“流”这个词到底是什么意思?它是从客户端发送的当前消息吗?客户端连接是否有能力发送更多消息?
如果客户从未告诉他关闭,为什么会
SocketChannel
在客户端关闭?read()
返回 -1 和对等 I/O 错误重置连接有什么区别?
这就是我阅读的方式SocketChannel
:
private JSONObject readIncomingData(SocketChannel socketChannel)
throws JSONException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException {
JSONObject returnObject = null;
ByteBuffer buffer = ByteBuffer.allocate(1024);
Charset charset = Charset.forName("UTF-8");
String endOfMesesage = "\"}";
String message = "";
StringBuilder input = new StringBuilder();
boolean continueReading = true;
while (continueReading && socketChannel.isOpen())
{
buffer.clear();
int bytesRead = socketChannel.read(buffer);
if (bytesRead == -1)
{
continueReading = false;
continue;
}
buffer.flip();
input.append(charset.decode(buffer));
message = input.toString();
if (message.contains(endOfMesesage))
continueReading = false;
}
if (input.length() > 0 && message.contains(endOfMesesage))
{
JSONObject messageJson = new JSONObject(input.toString());
returnObject = new JSONObject(encrypter.decrypt(messageJson.getString("m")));
}
return returnObject;
}