【发布时间】:2013-01-04 08:16:49
【问题描述】:
这不是我第一次尝试理解这个问题,但我希望这将是最后一个:
一些背景:
我有一个Java SocketChannel NIO 服务器在非阻塞模式下工作。
此服务器有多个客户端,它们从它发送和接收消息。
每个客户端每隔一段时间就会使用"keepalive" 消息保持与服务器的连接。
服务器的主要思想是客户端将“始终”保持连接并以“推送”模式接收来自它的消息。
现在回答我的问题:
在 Java NIO read() 函数中 - 当 read() 返回 -1 - 这意味着它的 EOS。
在我问过here 的问题中,我意识到这意味着套接字已完成其当前流并且不需要关闭..
在 google 中搜索更多关于此的内容时,我发现这确实意味着连接在另一端关闭..
“流”这个词到底是什么意思?它是从客户端发送的当前消息吗?客户端连接是否能够发送更多消息?
如果客户从未告诉他关闭
SocketChannel,为什么要在客户端关闭?read()return -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;
}
【问题讨论】:
标签: java nio socketchannel