Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.nio.channels.ClosedChannelException

Tags:

java

How can i solve this problem. I got following error:

java.nio.channels.ClosedChannelException

This is coding:

 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);
            }
        }
    }
}
like image 383
lakshmi Avatar asked May 10 '10 07:05

lakshmi


People also ask

What is Java NIO channels ClosedChannelException?

The class ClosedChannelException is invoked when an I/O operation is attempted on a closed channel or a channel that is closed to the attempted operation. That is if this exception is thrown, however, does not imply the channel is completely closed but is closed to the attempted operation.

What are NIO channels?

In Java NIO, the channel is a medium used to transports the data efficiently between the entity and byte buffers. It reads the data from an entity and places it inside buffer blocks for consumption. Channels act as gateway provided by java NIO to access the I/O mechanism.

What is channels in Java?

A channel represents an open connection to an entity such as a hardware device, a file, a network socket, or a program component that is capable of performing one or more distinct I/O operations, for example reading or writing. A channel is either open or closed.


2 Answers

You have closed the channel and are still trying to use it.

There are several issues with your code.

First, your test for EOS is faulty. Remove the limit() == 0 test. That doesn't indicate EOS, it just indicates a zero length read, which can happen in non-blocking mode at any time. It doesn't mean the peer has closed his end of the connection, and it doesn't mean you should close your end.

Second, closing a channel closes the socket as well. You should close the channel only, not the socket.

Third, closing a channel cancels the key. You don't need to follow every close with a cancel.

You may also have failed to check whether a ready key is valid in the select loop before using it, e.g. for reading.

I continue to be amazed, and amused, and bemused, by the claim elsewhere in this thread that 'source code is untrue' under some circumstances.

like image 171
user207421 Avatar answered Oct 28 '22 15:10

user207421


You need to fix/secure code that is throwing this exception. ClosedChannelException is ...

... thrown when an attempt is made to invoke or complete an I/O operation upon channel that is closed, or at least closed to that operation. That this exception is thrown does not necessarily imply that the channel is completely closed. A socket channel whose write half has been shut down, for example, may still be open for reading

(as described in Java 6 API)

But really, you would need to provide us code snipped and stack trace in order to get more detailed help.

like image 40
Piotr Pachalko Avatar answered Oct 28 '22 16:10

Piotr Pachalko