Unable to Create a Socket :java.net.ConnectException: Connection refused: connect

Débora picture Débora · Jan 11, 2012 · Viewed 23.3k times · Source

I am going to create a socket and get an InputStream. Here is how I try it.

try {
    final String serverIP = "111.111.111.111";
    final int serverPort = Integer.parseInt(server_port);
    final InetAddress serverAd=InetAddress.getByName(serverIP);
    final InetAddress localAd =InetAddress.getByName(local_ip);  
    final int localPort = 4040;

    Socket socket = new Socket(serverAd, serverPort, localAd, localPort);  
}  

But there is an exception thrown,

java.net.ConnectException: Connection refused: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at java.net.Socket.connect(Socket.java:478)
    at java.net.Socket.<init>(Socket.java:375)
    at java.net.Socket.<init>(Socket.java:276)
    at shootist.Porter.run(Porter.java:41)

Here the server sends me rtp data and server side is ok and confirmed. I sent invite and got 200 as well. If there is a problem in my IP and port, I think, all responses cannot delivered to my IP and given Ports. But it can't happen as the server sends me responses to my IP and given port number. How I can fix this issue? Where I am wrong and what?

Answer

Remy Lebeau picture Remy Lebeau · Jan 11, 2012

A "connection refused" error means the socket stack on the server machine received your connection request and intentionally refused to accept it. That happens for one of two possible reasons:

1) there is no listening socket running on the port you are trying to connect to.

2) there is a listening socket, but its backlog of pending connections is full, so there is no room to queue your request at that moment.

To differentiate between the two, try reconnecting a few times with a delay in between each attempt. If you get the same error consistently, then #1 is likely the culprit. Make sure the port number is correct. If #2 is the culprit, your reconnect has a chance of succeeding eventually.