java.net.ConnectException: Connection refused
The java.net.ConnectException: Connection refused exception is thrown when an application tries to connect to a remote host, but the connection is refused by the host. This can happen for several reasons, such as:
Java.net.ConnectException, commonly referred to as "connection refused," is a frequently encountered exception in Java networking. This issue occurs when a client tries to establish a connection with a server that either isn't accepting connections or cannot be reached.
- Explanation of the Problem
A client may face this error when attempting to create a connection with a server that is not ready to accept incoming connections. The server might be down, experiencing a high volume of traffic, or not running the service the client is trying to access.
Sample Stack Trace:
java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.Socket.connect(Socket.java:607)
at com.example.Client.main(Client.java:10)- Common Reasons for Connection Refusal
There are several reasons why a server might refuse a client's connection attempt, such as:
a. The server is not running: If the server application is not active, it won't accept incoming connections. b. An incorrect port number: A mismatched port number between the client and server will result in a connection refusal. c. Firewall restrictions: Firewalls can block incoming connections if not configured properly.
- How to Address the Issue
To resolve the connection refusal problem, follow these steps:
a. Verify the server is operational: Ensure the server application is running and capable of accepting connections. b. Double-check the port number: Make sure both the client and server are using the same port number for communication. c. Configure the firewall: Ensure the firewall is set up to allow incoming connections on the specified port.
Reproducing the Exception The following minimal client code demonstrates how the exception is thrown when connecting to a port with no active listener:
import java.net.ConnectException;
import java.net.Socket;
import java.io.IOException;
public class ConnectionRefusedExample {
public static void main(String[] args) {
try {
// Connect to localhost on a port where no server is listening
Socket socket = new Socket("localhost", 9999);
} catch (ConnectException e) {
System.err.println("Connection refused: " + e.getMessage());
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
}
}Handling and Retrying In production environments, transient connection refusals are common. Implementing a retry mechanism with proper exception handling is recommended:
import java.net.ConnectException;
import java.net.Socket;
import java.io.IOException;
public class RetryConnection {
public static void connectWithRetry(String host, int port, int maxRetries) {
int attempts = 0;
while (attempts < maxRetries) {
try {
Socket socket = new Socket(host, port);
System.out.println("Connected successfully!");
socket.close();
return;
} catch (ConnectException e) {
attempts++;
System.err.println("Attempt " + attempts + " failed: " + e.getMessage());
if (attempts < maxRetries) {
try { Thread.sleep(1000 * attempts); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); }
}
} catch (IOException e) {
System.err.println("Unexpected I/O error: " + e.getMessage());
break;
}
}
System.err.println("Failed to connect after " + maxRetries + " attempts.");
}
}