📜  如何修复Java.net.ConnectException:连接被拒绝:在Java连接?

📅  最后修改于: 2021-10-28 02:49:41             🧑  作者: Mango

Java.net.ConnectException:连接被拒绝:connect 是Java最常见的一种网络异常,只要软件处于客户端 – 服务器架构并试图建立从客户端到服务器的 TCP 连接。我们需要仔细处理异常以解决通信问题。首先我们来看一下Java.net.ConnectException: Connection denied发生的可能原因。

  1. 由于涉及客户端和服务器,两者都应该在局域网或互联网等网络中。如果它不存在,它将在客户端抛出异常。
  2. 如果服务器没有运行。通常端口如 8080, (for tomcat), 3000 or 4200 (for react/angular), 3306(MySQL), 27017(MongoDB) 或被其他一些代理占用或完全关闭,即实例未启动。
  3. 有时,由于某些覆盖设置等,服务器可能正在运行但未侦听端口。
  4. 通常,出于安全原因,防火墙会在那里,如果它禁止通信。
  5. 错误地,错误的端口是在给定的端口或随机端口代号中提到的。
  6. 连接字符串信息错误。例如:

实现:这里我们使用的是 MySQL 数据库连接,连接信息应该是这种格式。现在让我们看看修复Java .net.ConnectException: Connection denied 的方法。使用如下所示的命令 Ping 目标主机:

ping  - to test

ipconfig(for windows)/ifconfig(linux) - to get network configuration

netstat - statistical report

nslookup - DNS lookup name

有诸如“Putty”之类的工具可用于通信,它是用于 Windows 和 Unix 的 Telnet 和 SSH 的免费实现。

示例 1:创建Java .net.ConnectException 的简单Java代码

Java
// Main class
// TestHostNameAndPortConnectivity
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Hostname is defined so do have arbitrary
        // localhost value which is nothing but 127.0.0.1
        String hostname = "127.0.0.1";
 
        // PORT is defined here
        // It should have been 8080 or 8000 but cannot be 80
 
        // If IP and PORT is invalid it will get exception
        // Trying to connect
        int port = 80;
 
        // Try block to check for exceptions
        try (Socket socket = new Socket(hostname, port)) {
 
            // InputStream to read data from socket
            InputStream inputStream
                = socket.getInputStream();
            InputStreamReader inputStreamReader
                = new InputStreamReader(inputStream);
 
            int data;
 
            StringBuilder outputString
                = new StringBuilder();
            // Data read from input stream
            while ((data = inputStreamReader.read())
                   != -1) {
                outputString.append((char)data);
            }
        }
 
        // Catch block to handle the exceptions
        catch (IOException ex) {
 
            // If the given hostname and port number are
            // invalid, connectivity cannot be estabilished
            // and hence error thrown Exception will happen
            // when socket will not reachable
            System.out.println(
                "Connection Refused Exception as the given hostname and port are invalid : "
                + ex.getMessage());
        }
    }
}


Java
// Java Program to Demonstrate DB Connection Setup
 
// Importing basic libraries
import java.io.*;
import java.util.*;
// Step 1: Importing DB libearies
import.java.sql.*;
 
// Try block to check for exceptions
try {
 
    // Setting initial connection object to null
    Connection con = null;
 
    String driver = "com.mysql.jdbc.Driver";
 
    // Step 2: Loading and registering drivers
 
    // Here if IPADDRESS is not your localhost,
    // need to specify that or specific address
    String IPADDRESS = "localhost"
 
        // 3306 is port number
        String url1
        = "jdbc:mysql://IPADDRESS:3306/";
 
    // If noy suggesting that to assign generally is
    // followed as DB = mySQL username= root, password=1234
    String db = "";
    String dbUser = "";
    String dbPasswd = "";
 
    // Loading driver using forName() method
    Class.forName(driver).newInstance();
    // Registering driver using DriverManager
    con = DriverManager.getConnection(url1 + db, dbUser,
                                      dbPasswd);
 
    // Display message on the console
    // when the connection is successfully setup
    System.out.println("Database Connection Established");
}
 
// Catch block to handle the exceptions
catch (IOException ex) {
 
    // Exception will happen when the IPAddress and port
    // number are mismatch By pinging, we can correct that
 
    // Display message on the console and
    // getting exception message using getMessage() method
    System.out.println(
        "Connection Refused Exception as the given hostname and port are invalid : "
        + ex.getMessage());
}


输出:

示例 2: MySQL 连接检查

Java

// Java Program to Demonstrate DB Connection Setup
 
// Importing basic libraries
import java.io.*;
import java.util.*;
// Step 1: Importing DB libearies
import.java.sql.*;
 
// Try block to check for exceptions
try {
 
    // Setting initial connection object to null
    Connection con = null;
 
    String driver = "com.mysql.jdbc.Driver";
 
    // Step 2: Loading and registering drivers
 
    // Here if IPADDRESS is not your localhost,
    // need to specify that or specific address
    String IPADDRESS = "localhost"
 
        // 3306 is port number
        String url1
        = "jdbc:mysql://IPADDRESS:3306/";
 
    // If noy suggesting that to assign generally is
    // followed as DB = mySQL username= root, password=1234
    String db = "";
    String dbUser = "";
    String dbPasswd = "";
 
    // Loading driver using forName() method
    Class.forName(driver).newInstance();
    // Registering driver using DriverManager
    con = DriverManager.getConnection(url1 + db, dbUser,
                                      dbPasswd);
 
    // Display message on the console
    // when the connection is successfully setup
    System.out.println("Database Connection Established");
}
 
// Catch block to handle the exceptions
catch (IOException ex) {
 
    // Exception will happen when the IPAddress and port
    // number are mismatch By pinging, we can correct that
 
    // Display message on the console and
    // getting exception message using getMessage() method
    System.out.println(
        "Connection Refused Exception as the given hostname and port are invalid : "
        + ex.getMessage());
}

同样,对于其他数据库,我们需要为 MongoDB 指定正确的端口号,即 27017,如果存在 SSL(安全套接字层),则需要检查防火墙的事先检查,因此通过编码,我们可以提出解决方案克服异常