×

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

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

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.

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with...

3 minutes read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

Leap Year Program in Java

Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other...

2 minutes read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 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.

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.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

Java copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.