如何解决AsynchronousSocketChannel 结果在流结束时不返回 -1
我正在尝试设置一个 AsynchronousServerSocketChannel 来接受来自客户端的连接并根据需要发送和接收消息(不一定是请求->响应)。为方便起见,我使用带有单独完成处理程序的异步读取和写入调用。我现在遇到的问题是,当客户端断开连接时,传递给我的完成处理程序的结果不是 -1,并且胎面继续尝试读取。我希望我的服务器连接在相应的客户端连接关闭时自动关闭。
这是我的读取完成处理程序的代码:
class ReadHandler implements CompletionHandler<Integer,Attachment> {
@Override
public void completed(Integer result,Attachment att) {
if (result < 0) {
try {
System.out.println("Peer at " + att.clientAddr + " has disconnected.");
att.channel.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
att.readBuffer.flip();
int limits = att.readBuffer.limit();
byte bytes[] = new byte[limits];
att.readBuffer.get(bytes,limits);
att.readBuffer.clear();
if(att.hsDone) {
// process incoming msg
peer.processMessage(att.connectedPeerId,bytes);
} else { // if handshake has not been done
att.connectedPeerId = peer.processHandshake(bytes);
System.out.println("Shook hands with peer " + att.connectedPeerId + ".");
if(att.connectedPeerId < 0) {
try {
att.channel.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
att.hsDone = true;
att.writeBuffer.put(message.handshakeMsg(peer.id));
att.writeBuffer.flip();
WriteHandler handler = new WriteHandler();
att.channel.write(att.writeBuffer,att,handler);
}
}
att.readBuffer.flip();
att.channel.read(att.readBuffer,this);
}
}
@Override
public void failed(Throwable exc,Attachment att) {
System.err.println(exc.getMessage());
}
}
对于我的写入完成处理程序:
class WriteHandler implements CompletionHandler<Integer,Attachment att) {
att.writeBuffer.clear();
// check if msg needs to be sent
byte data[] = peer.getNextMsg(att.connectedPeerId);
att.writeBuffer.put(data);
att.writeBuffer.flip();
if(att.channel.isOpen())
att.channel.write(att.writeBuffer,this);
}
@Override
public void failed(Throwable exc,Attachment att) {
System.err.println(exc.getMessage());
}
}
对解决此问题的任何帮助表示感谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。