NIO client giving exception : Connection refused: no further information

ConnectException: connection refused means nothing was listening at the IP:port you tried to connect to, or on some platforms that the server's listen-backlog queue filled up. If it is thrown and you catch it correctly, you will certainly catch it. You would have to expand on what actually happens and what your actual catch code looks like for further assistance.

However you have many other problems:

private void connect(SelectionKey key) throws IOException {
    SocketChannel channel = (SocketChannel);
            System.out.println("* Here *");

At this point, if finishConnect() returned false, you should return. You should not fall through and re-register the channel for OP_WRITE. The connection is still pending. Printing "* Here *" is also pretty futile. Try printing something meaningful.

    catch(ConnectException e)
        System.out.println("BP 1");


You should certainly close the channel at this point. It is of no further use to man or beast.


Closing the channel cancels the key. Remove wherever encountered.


As above, you should certainly return at this point.

    /*if (channel.isConnectionPending()){
            System.out.println("not connected");

Get rid of this crud. It is never appropriate to spin-loop in non-blocking mode. Don't even leave it lying around as comments: some idiot may come along later and play with putting it back.


The channel is already in non-blocking mode. Otherwise you wouldn't be here. Remove.

    channel.register(selector, SelectionKey.OP_WRITE);

Another way to do that is key.interestOps(SelectionKey.OP_WRITE);

Sleeping in networking code is literally a waste of time. It doesn't solve anything.

You are assuming that write() succeeded completely, and you're ignoring the count it returns.

You're using a fairly poor quality reference:

  • Same remarks about write() apply as above.
  • flip() is not 'like a reset'.
  • Cancelling a key closes the channel.
  • You don't have to clear a brand-new ByteBuffer, but in any case allocating a ByteBuffer per read is poor practice.
  • ServerSocketChannel.accept() can return null.
  • The code that displays a String after reading is incorrect.
  • There is no need to use a Map when keys have attachments.
  • There's no need to keep testing Thread.interrupted() when NIO is interruptible anyway.
  • There's no need to close everything just becaues of one IOException on one channel.

Try to find something better.