gpt4 book ai didi

java.nio.channels.ClosedChannelException

转载 作者:搜寻专家 更新时间:2023-10-30 20:00:56 25 4
gpt4 key购买 nike

我该如何解决这个问题。我收到以下错误:

java.nio.channels.ClosedChannelException

这是编码:

 public void run() {

try {
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(512);
int i1 = socketChannel.read(buffer);

if (buffer.limit() == 0 || i1 == -1) {

Socket s = null;
try {
s = socketChannel.socket();
s.close();
key.cancel();
} catch (IOException ie) {
if (UnitDataServer.isLog) {
log.error("Error closing socket " + s + ": " + ie);
}
}
} else {
buffer.flip();
if (UnitDataServer.isLog) {
log.info(" Recvd Message from Unit : " + buffer.array());
}
byte byteArray[] = buffer.array();
log.info("Byte Array length :" + byteArray.length);
hexString = new StringBuffer();

for (int i = 0; i < i1 /* byteArray.length */; i++) {
String hex = Integer.toHexString(0xFF & byteArray[i]);
if (hex.length() == 1) {
// could use a for loop, but we're only dealing with a
// single byte
hexString.append('0');
}
hexString.append(hex);
}
hexString.trimToSize();
log.info("Hex String :" + hexString);

Communicator.dataReceive(new DataReceive(
socketChannel, hexString.toString(), dst));

}
} catch (Exception e) {
if (UnitDataServer.isLog) {
// log.error(e);
}
try {
socketChannel.socket().close();
key.cancel();
} catch (IOException ex) {
if (UnitDataServer.isLog) {
log.error(ex);
}
}
}
}

最佳答案

您已关闭 channel 并仍在尝试使用它。

您的代码有几个问题。

首先,您对 EOS 的测试有误。删除 limit() == 0 测试。这并不表示 EOS,它只是表示零长度读取,这在任何时候都可能在非阻塞模式下发生。这并不意味着对方已经关闭了他的连接端,也不意味着你应该关闭你的端。

其次,关闭 channel 也会关闭套接字。您应该只关闭 channel ,而不是套接字。

第三,关闭 channel 取消 key 。您无需在每次收盘后都取消。

您可能还没有在使用之前检查就绪键在选择循环中是否有效,例如阅读。

在某些情况下,该线程中其他地方的“源代码不真实”的说法让我感到惊讶、好笑和困惑。

关于java.nio.channels.ClosedChannelException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2801087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com