×

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

Sphenic Number in Java

In this section, we will learn what is a sphenic number is and show you how to write Java programmes to determine if a specific number are sphenic or not....

3 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Java Math scalb() Method

The scalb() method of Java Math class returns a single perfectly rounded product of floating-point and member of the double value set as if performed by d*2scaleFacor rounded value. Syntax: public static...

2 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

flour pack problem in Java

Create a method called canPack and give it three int parameters: bigCount, smallCount, and objective. The bigCount option indicates the number of large flour bags (5 kilos each). The smallCount argument indicates...

3 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

String Coding Interview Questions in Java

What is String in Java?In Java, a String is a Class that is defined in the java.lang package. It isn't a basic data type like int or long. Character Strings...

5 minutes read.

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 minutes read.

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.

Java Thread Lifecycle: States and Stages

Multithreading Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process...

7 minutes read.