×

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make a TCP association from the client to the server. We want to deal with the special case cautiously to satisfy the correspondence issue.

The java.net.ConnectException special case is one of the most widely recognized Java exemptions connected with systems administration. We might experience it while we're laying out a TCP association from a client application to a server. As it's a checked exemption, we ought to deal with it appropriately in our code in an attempt to get a block.

Reasons for java.net.ConnectionException: connection refused Exception

  1. On the off chance that the server isn't running. Generally, ports like 8080 (for tomcat), 3000 or 4200 (for respond/rakish), 3306(MySQL), 27017(MongoDB) or involved by a few different specialists or thoroughly down, for example, an occasion not began.
  2. Here and there, a server might be running, however, not tuning in on port in light of some superseded settings and so forth.
  3. Ordinarily, for the sake of security, the Firewall will be there, and in the event that it refuses the correspondence.
  4. Accidentally, some unacceptable port is referenced in the port or the arbitrary port age number given.
  5. Association string data wrong: for example, while connecting the database using JDBC, if we give a wrong password, the Exception may rise.
  6. As client and server included, both ought to be in an organization like LAN or web. It will toss an exemption on the client side.
  7. The server we are attempting to interface with is basically not begun. In this manner, we can't get an association.
  8. The host and port mix we are utilizing to interface with the server may be erroneous
  9. A firewall could hinder associations from explicit IP locations or ports

Example 1:

Example program to show the java.net.ConnectionException Exception:

// program to demonstrate the java.net.Connection Exception
import java.io.*;
import java.net.*;
importjava.util.*;
// class with main
public class HelloWorld {
public static void main(String[] args)
{
    // main method
// defining the local hostname and the value of the local host is 127.0.0.1
String host = "127.0.0.1";
// defining the port and the port id must be 8080 or 8000
// the post id should not be 100 
// if it is rather than 8080 or 8000 the exception rises
int port = 100;
// Try block to check for exceptions
try (Socket so = new Socket(host, port)) {
// defining an InputStream to read the socket data
InputStream input = so.getInputStream();
InputStreamReaderis = new InputStreamReader(input);
int da;
StringBuilder output= new StringBuilder();
// reading the data from the input stream
while ((da = isr.read())!= -1) {
output.append((char)da);
}
}
// Handling the Exception using catch block
catch (IOException e) {


/* If the given hostname and port number are invalid, the network can't be laid out, and consequently blunder is tossed Exception will happen when the attachment will not be reachable */
System.out.println("Connection Refused Exception as the given hostname and port are invalid : "+ e.getMessage());
}
}
}

Output:

Java.net.ConnectionException

the output is: Java -cp /tmp/9BLwnhzXAr HelloWorld

Connection Refused Exception as the given hostname and port are invalid: Connection refused (Connection refused)

Example 2:

A program to setup database connection

// java program to setup the connection between the Java and database
import java.io.*;
importjava.util.*;
importjava.sql.*; // importing sql package
classHelloWorld
{
public static void main(String args[])
    {
// checking the Exception using the try block
try {
// initializing the connection object value as NULL
Connection connect = null;
String dr = "com.MySQL.jdbc.Driver";
// Step 2: loading the driver class 
// Here, in the event that IP address isn't your localhost, need to determine that or explicit location
String IP = "local"
// giving the port id as 3306
String urlmysql://IPADDRESS:3306/= "JDBC:mysql://IP:3306/
// followed as DB = MySQL username= Scott, password=tiger
String DB = "<your dbname>";
String dbUser = "<username>";
String dbPasswd = "<password>";
// By using the forName() method, we are loading the driver class
Class.forName(driver).newInstance();
// making the connection using the connection manager
co = DriverManager.getConnection(url1 + DB, dbUser,dbPasswd);


// Displaying the successful message if the connection is set up successful
System.out.println(" The database connected sucessfully");
}
// Handling the Exception using the catch block
catch (IOException e) {
// Exemption will happen when the IPAddress and port number are confounded By pinging. We can address that
System.out.println("Connection Refused Exception as the given hostname and port are invalid : "+ e.getMessage());
}
}
}

Related Topics

How to enable java in chrome

The Java module is huge for the Java Runtime Environment (JRE). It permits a program to work with the Java stage to run Java applets. Essentially, each of the undertakings connect...

3 minutes read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

Java Math cbrt() Method

The cbrt() method of Math class returns the cube root of a double value. Syntax: public static double cbrt(double a) Parameters: The parameter ‘a’ represents the value whose cube root is to be determined. Return...

2 minutes read.

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

Java Read File

Java provides its users with many ways of reading a file. To read a text file, you can use a FileReader, BufferedReader, or Scanner. Each utility offers something special for...

6 minutes read.

Java Math sin() Method

The sin() method of Java Math class returns the trigonometric sine of the specified angle. Syntax: public static double sin(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The sin() method...

1 minute read.

StringBuilder in Java

StringBuilder in Java Java StringBuilder class is introduced since JDK 1.5. The StringBuilder class is mainly used to create modifiable or mutable strings. Note that the StringBuilder class is not synchronized....

7 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.