Reputation: 314
I am trying to write a simple program to open a socket channel to a local address. I get a connection refused exception whenever I run this program
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
public class testSocket {
public static void main(String [] args) {
try {
InetAddress addr = InetAddress.getByName("localhost");
InetSocketAddress remoteAddress = new InetSocketAddress(addr, 19015);
// Open a new Socket channel and set it to non-blocking
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
// Issue the Connect call on the remote address.
socketChannel.connect(remoteAddress);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The exception that I get is
java.net.ConnectException: Connection refused
at sun.nio.ch.Net.connect(Native Method)
at sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:464)
at testSocket.main(testSocket.java:17)
I encounter this issue with Sun Solaris and HP - UX. It seems to work fine on a Linux machine. Can anyone let me know why the connection is being refused? I did a netstat -a and confirmed that the port is not in use.
Thanks in advance!
Upvotes: 1
Views: 19854
Reputation: 29139
From the Javadoc for SocketChannel.connect()
If this channel is in non-blocking mode then an invocation of this method initiates a non-blocking connection operation. If the connection is established immediately, as can happen with a local connection, then this method returns true. Otherwise this method returns false and the connection operation must later be completed by invoking the finishConnect method.
When I run your code on Linux, connect() returns false hence there is no exception. If you add a call to socketChannel.finishConnect() you will see the same connection refused exception as you get on Solaris/HP-UX.
I suspect that on Solaris/HP-UX connect() returns true hence the exception is thrown immediately.
Upvotes: 1
Reputation: 21184
The "Connection refused" message is what you'll receive when there is no process listening on your specified port (19015). It looks like you're trying to connect to a service that isn't there. netstat is even telling you that the port isn't in use!
Upvotes: 1