java.nio.channels.ClosedChannelException

标签 java

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

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/

相关文章:

java - 在单元测试 Controller 时模拟 Spring Validator

java - 在注释中传递方法

java - 获取每个线程的线程组信息

java - 如何使用 Avro 在 Spring Kafka 1.3 中移动过去不可反序列化的消息

java - 使用斯坦福 OpenIE 进行子句分割

java - Drawable不会在SurfaceView上绘制,Thread实现,不重写onDraw

java - 如果已启用,则隐藏 JComboBox 的按钮

java - 在 java 中监视文件夹中新文件的最佳 API

java - 为什么这个 JSON 字符串无效? jQuery.parseJSON 函数抛出无效字符

java - SalesForce 上有效 SAML2.0 断言的 invalid_grant 错误