Ошибка java net connect

Перейти к содержанию

При попытке подключения к серверу «Майнкрафт» пользователь может столкнуться с сообщением «Java.net.ConnectException: Connection timed out: no further information». Появление данного сообщения обычно сигнализирует о возникновении различного рода сетевых проблем при получении доступа к игровому серверу, из-за чего желание пользователя насладиться игровыми мирами «Майнкрафт» остаётся нереализованным. Ниже я разберу суть данной дисфункции, опишу её причины, а также поясню, как исправить ошибку Java.net.ConnEctexception на вашем ПК.

Сообщение Java.net.ConnectException

Содержание

  1. Connection timed out: no further information – особенности дисфункции
  2. Как исправить «Java.net.ConnectException: Connection timed out»
  3. Заключение

Connection timed out: no further information – особенности дисфункции

В переводе текст данного сообщения выглядит примерно как «Сетевой сбой Java. Время соединения истекло: дальнейшая информация отсутствует».

Указанная ошибка Java.net.ConnectException обычно возникает во время подключения к серверу игры «Майнкрафт», но также фиксировались спорадические случаи появления данной ошибки при работе других продуктов, использующих «Java» (к примеру, на «Azure notification hub»).

Появление проблемы «Java.net.ConnectException: Connection timed out: no further information» имеет следующие причины:

  • Пользователь использует нестабильное сетевое соединение с медленным интернетом;
  • На ПК пользователя установлена устаревшая версия «Java»;
  • Пользователь пользуется устаревшей версией «Майнкрафт»;
  • Наблюдаются сбои в работе игрового сервера, к которому пробует подключиться пользователь (ресурс не доступен, проходят технические работы и др.);
  • Антивирус или брандмауэр блокирует подключения к игровому серверу;
  • Пользователь использует динамический IP;
  • Пользовательский роутер работает некорректно.

Как исправить «Java.net.ConnectException: Connection timed out»

Существуют несколько способов избавиться от ошибки Java.net.ConnectException. Рассмотрим их по порядку:

  • Перезагрузите ваш PC. В некоторых случаях данный простой метод позволял решить ошибку java.net.connectexception connection refused;
  • Установите на ПК свежую версию «Java». Довольно частой причиной рассматриваемой проблемы является устаревшая версия «Java» на пользовательском ПК. Перейдите в Панель управления, затем в «Программы», там найдите «Java» и кликните на неё. После появления окна её настроек перейдите на вкладку «Update», нажмите там на кнопку «Update Now», и установите в системе требуемые обновления.

Данную процедуру необходимо провести как на вашей машине, так и на машине того пользователя, с которым вы собираетесь играть в «Майнкрафт» по сети;

Кнопка

  • Внесите «Майнкрафт» в исключения брандмауэра и антивируса на вашем ПК. Запустите Панель управления, перейдите в «Система и безопасность», там найдите «Брандмауэр Виндовс» и кликните на него. В открывшемся окне настроек брандмауэра слева сверху выберите опцию «Разрешения взаимодействия…».Опция разрешения взаимодействияВ открывшемся окне разрешённых для внешнего подключения программ найдите программы с упоминанием «Java», и поставьте им галочки для разрешения подключения (поможет кнопка «Изменить параметры»). Нажимаем на «Ок» для сохранения результата, перезагружаемся и пробуем подключиться к серверу. С антивирусом необходимо проделать аналогичные операции, внеся «Java» и «Майнкрафт» в его исключения;
  • Попробуйте альтернативный сервер. Если подключения к конкретному серверу невозможно, тогда вполне вероятно, что у него наблюдаются временные проблемы в работе. Рекомендую попробовать альтернативный сервер, или подождать некоторое время, пока работоспособность начального сервера восстановиться;
  • Создайте сервер на другой машине. Если вы создаёте сервер, к которому подключается другой знакомый вам пользователь, тогда рекомендуется поменять базовый компьютер для создания сервера. То есть сервер должен создать уже другой пользователь, а вы подключитесь к нему. Часто это позволяло решить проблему net.ConnectException на пользовательском компьютере;
  • Используйте статистический IP-адрес. Если у вас есть возможность, рекомендуется использовать официальный (белый) IP-адрес, полученный через провайдера (обычно данная услуга имеет платный характер);
  • Установите на ваш ПК (гаджет) свежую версию «Майнкрафт». Обычно необходимо, чтобы версии игры на сервере и на вашем ПК (гаджете) соответствовали друг другу; Картинка MINECRAFT
    Установите самую свежую версию программы
  • Избавьтесь от имеющихся модов к игре. Если вы используете какие-либо моды «Майнкрафт», рекомендуется удалить их, оставив само тело игры;
  • Перезагрузите ваш роутер. Отключите ваш роутер, подождите полминуты, а затем включите его обратно;
  • Обратитесь за консультацией к провайдеру. По различным причинам некоторые провайдеры блокируют доступ к некоторым серверам. Узнайте, не ваш ли это случай, и не является ли ваш провайдер причиной возникновения данной проблемы.

Заключение

Наиболее распространёнными причинами ошибки «Java.net.ConnectException: Connection timed out: no further information» является устаревание пользовательской версии «Java» и блокировка брандмауэром подключения к нужному игровому серверу. Решением проблемы станет выполнение перечисленных выше советов, это позволит исправить ошибку Java.net.ConnectException на вашем ПК.

Опубликовано 21.03.2018 Обновлено 03.12.2020

Ошибка java.net.ConnectException: Connection refused является одним из самых распространенных сетевых исключений в Java. Эта ошибка возникает, когда вы работаете с архитектурой клиент-сервер и пытаетесь установить TCP-соединение от клиента к серверу.

Соединение также происходит в случае RMI (удаленного вызова метода), потому что RMI также использует протокол TCP-IP. При написании кода клиентского сокета на Java вы всегда должны обеспечивать правильную обработку этого исключения.

В этом руководстве по Java вы узнаете, почему возникает исключение при отказе в соединении и как решить проблему.

Причины

ошибка java.net.ConnectException: Connection refused

Отказ в соединении – это явный случай, когда клиент пытается подключиться через порт TCP, но не может это сделать. Вот некоторые из возможных причин, почему это происходит:

  1. Клиент и Сервер, один или оба из них не находятся в сети.

Да, возможно, что они не подключены к локальной сети, Интернету или любой другой сети.

  1. Сервер не работает.

Вторая наиболее распространенная причина – сервер не работает. Вы можете использовать следующие сетевые команды, например, ping, чтобы проверить, работает ли сервер.

  1. Сервер работает, но не видит порт, к которому клиент пытается подключиться.

Это еще одна распространенная причина возникновения «java.net.ConnectException: соединение отклонено», когда сервер работает, но видит другой порт. Трудно разобраться в этом случае, пока вы не проверите конфигурацию.

  1. Брандмауэр запрещает комбинацию хост-порт.

Почти каждая корпоративная сеть защищена. Если вы подключаетесь к сети других компаний, вам нужно убедиться, что они разрешают друг другу IP-адрес и номер порта.

  1. Неверная комбинация хост-портов.

Проверьте последнюю конфигурацию на стороне клиента и сервера, чтобы избежать исключения отказа в соединении.

  1. Неверный протокол в строке подключения.

TCP является базовым протоколом для многих высокоуровневых протоколов, включая HTTP, RMI и другие. Нужно убедиться, что вы передаете правильный протокол, какой сервер ожидает.

Если вам интересно узнать больше об этом, то изучите книгу по сетевым технологиям, такую ​​как Java Network Programming (4-е дополнение), написанную Гарольдом Эллиоттом Расти.

Java Network Programming

Простое решение состоит в том, чтобы сначала выяснить фактическую причину исключения. Здесь важнее всего подход к поиску правильной причины и решения. Как только вы узнаете реальную причину, вам, возможно, даже не потребуется вносить какие-либо существенные изменения.

Вот несколько советов, которые могут помочь исправить ошибку java.net.ConnectException: Connection refused:

  1. Сначала попытайтесь пропинговать целевой хост, если хост способен пинговать, это означает, что клиент и сервер находятся в сети.
  2. Попробуйте подключиться к хосту и порту сервера, используя telnet. Если вы можете подключиться, значит что-то не так с вашим клиентским кодом. Кроме того, наблюдая за выводом telnet, вы узнаете, работает ли сервер или нет, или сервер отключает соединение.

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    java.net.ConnectException: Connection refused: connect is the most frequent kind of occurring networking exception in Java whenever the software is in client-server architecture and trying to make a TCP connection from the client to the server. We need to handle the exception carefully in order to fulfill the communication problem. First, let us see the possible reasons for the occurrence of java.net.ConnectException: Connection refused.

    1. As client and server involved, both should be in a network like LAN or internet. If it is not present, it will throw an exception on the client-side.
    2. If the server is not running. Usually ports like 8080, (for tomcat), 3000 or 4200 (for react/angular), 3306(MySQL), 27017(MongoDB) or occupied by some other agents or totally down i.e. instance not started.
    3. Sometimes a server may be running but not listening on port because of some overridden settings etc.
    4. Usually, for security reasons, the Firewall will be there, and if it is disallowing the communication.
    5. By mistake, the wrong port is mentioned in the port or the random port generation number given.
    6. Connection string information wrong. For example:

    Connection conn = DriverManager.getConnection(“jdbc:mysql://localhost/:3306<dbname>?” + “user=<username>&password=<password>”);

    Implementation: Here we are using MySQL database connectivity and connection info should be of this format. Now let us see the ways to fixing the ways of java.net.ConnectException: Connection refused. Ping the destination host by using the commands as shown below:

    ping <hostname> - to test
    
    ipconfig(for windows)/ifconfig(linux) - to get network configuration
    
    netstat - statistical report

    nslookup - DNS lookup name

    There are tools like “Putty” are available to communicate, and it is a free implementation of Telnet and SSH for Windows and Unix.

    Example 1: 

    import java.io;

    import java.net.*;

    import java.util.*;

    public class GFG {

        public static void main(String[] args)

        {

            String hostname = "127.0.0.1";

            int port = 80;

            try (Socket socket = new Socket(hostname, port)) {

                InputStream inputStream

                    = socket.getInputStream();

                InputStreamReader inputStreamReader

                    = new InputStreamReader(inputStream);

                int data;

                StringBuilder outputString

                    = new StringBuilder();

                while ((data = inputStreamReader.read())

                       != -1) {

                    outputString.append((char)data);

                }

            }

            catch (IOException ex) {

                System.out.println(

                    "Connection Refused Exception as the given hostname and port are invalid : "

                    + ex.getMessage());

            }

        }

    }

    Output:

    Example 2: MySQL connectivity Check

    Java

    import java.io.*;

    import java.util.*;

    import java.sql.*;

    try {

        Connection con = null;

        String driver = "com.mysql.jdbc.Driver";

        String IPADDRESS = "localhost"

            String url1

        String db = "<your dbname>";

        String dbUser = "<username>";

        String dbPasswd = "<password>";

        Class.forName(driver).newInstance();

        con = DriverManager.getConnection(url1 + db, dbUser,

                                          dbPasswd);

        System.out.println("Database Connection Established");

    }

    catch (IOException ex) {

        System.out.println(

            "Connection Refused Exception as the given hostname and port are invalid : "

            + ex.getMessage());

    }

    Similarly, for other DB, we need to specify the correct port number i.e. 27017 for MongoDB be it in case of SSL (Secure socket layer) is there, prior checks of Firewall need to be checked and hence via coding we can suggest the solutions to overcome the exception 

    Conclusion: As readymade commands like ping, telnet, etc are available and tools like putty are available, we can check the connectivity information and overcome the exception.

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    java.net.ConnectException: Connection refused: connect is the most frequent kind of occurring networking exception in Java whenever the software is in client-server architecture and trying to make a TCP connection from the client to the server. We need to handle the exception carefully in order to fulfill the communication problem. First, let us see the possible reasons for the occurrence of java.net.ConnectException: Connection refused.

    1. As client and server involved, both should be in a network like LAN or internet. If it is not present, it will throw an exception on the client-side.
    2. If the server is not running. Usually ports like 8080, (for tomcat), 3000 or 4200 (for react/angular), 3306(MySQL), 27017(MongoDB) or occupied by some other agents or totally down i.e. instance not started.
    3. Sometimes a server may be running but not listening on port because of some overridden settings etc.
    4. Usually, for security reasons, the Firewall will be there, and if it is disallowing the communication.
    5. By mistake, the wrong port is mentioned in the port or the random port generation number given.
    6. Connection string information wrong. For example:

    Connection conn = DriverManager.getConnection(“jdbc:mysql://localhost/:3306<dbname>?” + “user=<username>&password=<password>”);

    Implementation: Here we are using MySQL database connectivity and connection info should be of this format. Now let us see the ways to fixing the ways of java.net.ConnectException: Connection refused. Ping the destination host by using the commands as shown below:

    ping <hostname> - to test
    
    ipconfig(for windows)/ifconfig(linux) - to get network configuration
    
    netstat - statistical report

    nslookup - DNS lookup name

    There are tools like “Putty” are available to communicate, and it is a free implementation of Telnet and SSH for Windows and Unix.

    Example 1: 

    Java

    import java.io;

    import java.net.*;

    import java.util.*;

    public class GFG {

        public static void main(String[] args)

        {

            String hostname = "127.0.0.1";

            int port = 80;

            try (Socket socket = new Socket(hostname, port)) {

                InputStream inputStream

                    = socket.getInputStream();

                InputStreamReader inputStreamReader

                    = new InputStreamReader(inputStream);

                int data;

                StringBuilder outputString

                    = new StringBuilder();

                while ((data = inputStreamReader.read())

                       != -1) {

                    outputString.append((char)data);

                }

            }

            catch (IOException ex) {

                System.out.println(

                    "Connection Refused Exception as the given hostname and port are invalid : "

                    + ex.getMessage());

            }

        }

    }

    Output:

    Example 2: MySQL connectivity Check

    Java

    import java.io.*;

    import java.util.*;

    import java.sql.*;

    try {

        Connection con = null;

        String driver = "com.mysql.jdbc.Driver";

        String IPADDRESS = "localhost"

            String url1

        String db = "<your dbname>";

        String dbUser = "<username>";

        String dbPasswd = "<password>";

        Class.forName(driver).newInstance();

        con = DriverManager.getConnection(url1 + db, dbUser,

                                          dbPasswd);

        System.out.println("Database Connection Established");

    }

    catch (IOException ex) {

        System.out.println(

            "Connection Refused Exception as the given hostname and port are invalid : "

            + ex.getMessage());

    }

    Similarly, for other DB, we need to specify the correct port number i.e. 27017 for MongoDB be it in case of SSL (Secure socket layer) is there, prior checks of Firewall need to be checked and hence via coding we can suggest the solutions to overcome the exception 

    Conclusion: As readymade commands like ping, telnet, etc are available and tools like putty are available, we can check the connectivity information and overcome the exception.

    I’m trying to implement a TCP connection, everything works fine from the server’s side but when I run the client program (from client computer) I get the following error:

    java.net.ConnectException: Connection refused
            at java.net.PlainSocketImpl.socketConnect(Native Method)
            at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
            at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
            at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
            at java.net.Socket.connect(Socket.java:529)
            at java.net.Socket.connect(Socket.java:478)
            at java.net.Socket.<init>(Socket.java:375)
            at java.net.Socket.<init>(Socket.java:189)
            at TCPClient.main(TCPClient.java:13)
    

    I tried changing the socket number in case it was in use but to no avail, does anyone know what is causing this error & how to fix it.

    The Server Code:

    //TCPServer.java
    
    import java.io.*;
    import java.net.*;
    
    class TCPServer {
        public static void main(String argv[]) throws Exception {
            String fromclient;
            String toclient;
    
            ServerSocket Server = new ServerSocket(5000);
    
            System.out.println("TCPServer Waiting for client on port 5000");
    
            while (true) {
                Socket connected = Server.accept();
                System.out.println(" THE CLIENT" + " " + connected.getInetAddress()
                        + ":" + connected.getPort() + " IS CONNECTED ");
    
                BufferedReader inFromUser = new BufferedReader(
                        new InputStreamReader(System.in));
    
                BufferedReader inFromClient = new BufferedReader(
                        new InputStreamReader(connected.getInputStream()));
    
                PrintWriter outToClient = new PrintWriter(
                        connected.getOutputStream(), true);
    
                while (true) {
    
                    System.out.println("SEND(Type Q or q to Quit):");
                    toclient = inFromUser.readLine();
    
                    if (toclient.equals("q") || toclient.equals("Q")) {
                        outToClient.println(toclient);
                        connected.close();
                        break;
                    } else {
                        outToClient.println(toclient);
                    }
    
                    fromclient = inFromClient.readLine();
    
                    if (fromclient.equals("q") || fromclient.equals("Q")) {
                        connected.close();
                        break;
                    } else {
                        System.out.println("RECIEVED:" + fromclient);
                    }
    
                }
    
            }
        }
    }
    

    The Client Code:

    //TCPClient.java
    
    import java.io.*;
    import java.net.*;
    
    class TCPClient {
        public static void main(String argv[]) throws Exception {
            String FromServer;
            String ToServer;
    
            Socket clientSocket = new Socket("localhost", 5000);
    
            BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
                    System.in));
    
            PrintWriter outToServer = new PrintWriter(
                    clientSocket.getOutputStream(), true);
    
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
                    clientSocket.getInputStream()));
    
            while (true) {
    
                FromServer = inFromServer.readLine();
    
                if (FromServer.equals("q") || FromServer.equals("Q")) {
                    clientSocket.close();
                    break;
                } else {
                    System.out.println("RECIEVED:" + FromServer);
                    System.out.println("SEND(Type Q or q to Quit):");
    
                    ToServer = inFromUser.readLine();
    
                    if (ToServer.equals("Q") || ToServer.equals("q")) {
                        outToServer.println(ToServer);
                        clientSocket.close();
                        break;
                    } else {
                        outToServer.println(ToServer);
                    }
                }
            }
        }
    }
    

    Ashish Aggarwal's user avatar

    asked Jul 29, 2011 at 16:37

    Samantha Catania's user avatar

    Samantha CataniaSamantha Catania

    5,0085 gold badges42 silver badges69 bronze badges

    8

    This exception means that there is no service listening on the IP/port you are trying to connect to:

    • You are trying to connect to the wrong IP/Host or port.
    • You have not started your server.
    • Your server is not listening for connections.
    • On Windows servers, the listen backlog queue is full.

    tk_'s user avatar

    tk_

    15.8k8 gold badges80 silver badges89 bronze badges

    answered Jul 29, 2011 at 16:41

    Collin Price's user avatar

    Collin PriceCollin Price

    5,5403 gold badges34 silver badges35 bronze badges

    9

    I would check:

    • Host name and port you’re trying to connect to
    • The server side has managed to start listening correctly
    • There’s no firewall blocking the connection

    The simplest starting point is probably to try to connect manually from the client machine using telnet or Putty. If that succeeds, then the problem is in your client code. If it doesn’t, you need to work out why it hasn’t. Wireshark may help you on this front.

    answered Jul 29, 2011 at 16:39

    Jon Skeet's user avatar

    Jon SkeetJon Skeet

    1.4m850 gold badges9042 silver badges9132 bronze badges

    4

    You have to connect your client socket to the remote ServerSocket. Instead of

    Socket clientSocket = new Socket("localhost", 5000);

    do

    Socket clientSocket = new Socket(serverName, 5000);

    The client must connect to serverName which should match the name or IP of the box on which your ServerSocket was instantiated (the name must be reachable from the client machine). BTW: It’s not the name that is important, it’s all about IP addresses…

    user207421's user avatar

    answered Jul 29, 2011 at 17:21

    home's user avatar

    6

    I had the same problem, but running the Server before running the Client fixed it.

    answered Jul 25, 2012 at 18:09

    Dao Lam's user avatar

    Dao LamDao Lam

    2,81711 gold badges36 silver badges44 bronze badges

    3

    One point that I would like to add to the answers above is my experience

    «I hosted on my server on localhost and was trying to connect to it through an android emulator by specifying proper URL like http://localhost/my_api/login.php . And I was getting connection refused error«

    Point to note — When I just went to browser on the PC and use the same URL (http://localhost/my_api/login.php) I was getting correct response

    so the Problem in my case was the term localhost which I replaced with the IP for my server (as your server is hosted on your machine) which made it reachable from my emulator on the same PC.


    To get IP for your local machine, you can use ipconfig command on cmd
    you will get IPv4 something like 192.68.xx.yy
    Voila ..that’s your machine’s IP where you have your server hosted.
    use it then instead of localhost

    http://192.168.72.66/my_api/login.php


    Note — you won’t be able to reach this private IP from any node outside this computer. (In case you need ,you can use Ngnix for that)

    answered Feb 26, 2018 at 16:50

    eRaisedToX's user avatar

    eRaisedToXeRaisedToX

    3,1212 gold badges20 silver badges28 bronze badges

    0

    I had the same problem with Mqtt broker called vernemq.but solved it by adding the following.

    1. $ sudo vmq-admin listener show

    to show the list o allowed ips and ports for vernemq

    1. $ sudo vmq-admin listener start port=1885 -a 0.0.0.0 --mountpoint /appname --nr_of_acceptors=10 --max_connections=20000

    to add any ip and your new port. now u should be able to connect without any problem.

    Hope it solves your problem.
    enter image description here

    answered Apr 5, 2016 at 7:58

    MrOnyancha's user avatar

    MrOnyanchaMrOnyancha

    6065 silver badges28 bronze badges

    1

    Hope my experience may be useful to someone. I faced the problem with the same exception stack trace and I couldn’t understand what the issue was. The Database server which I was trying to connect was running and the port was open and was accepting connections.

    The issue was with internet connection. The internet connection that I was using was not allowed to connect to the corresponding server. When I changed the connection details, the issue got resolved.

    answered Nov 17, 2014 at 12:01

    phoenix's user avatar

    phoenixphoenix

    9653 gold badges16 silver badges38 bronze badges

    In my case, I gave the socket the name of the server (in my case «raspberrypi»), and instead an IPv4 address made it, or to specify, IPv6 was broken (the name resolved to an IPv6)

    answered Dec 21, 2016 at 18:20

    Zhyano's user avatar

    ZhyanoZhyano

    3691 gold badge3 silver badges13 bronze badges

    In my case, I had to put a check mark near Expose daemon on tcp://localhost:2375 without TLS in docker setting (on the right side of the task bar, right click on docker, select setting)

    answered Aug 23, 2017 at 13:42

    user1419243's user avatar

    user1419243user1419243

    1,6453 gold badges18 silver badges32 bronze badges

    i got this error because I closed ServerSocket inside a for loop that try to accept number of clients inside it (I did not finished accepting all clints)

    so be careful where to close your Socket

    user207421's user avatar

    answered May 21, 2016 at 21:07

    Basheer AL-MOMANI's user avatar

    I had same problem and the problem was that I was not closing socket object.After using socket.close(); problem solved.
    This code works for me.

    ClientDemo.java

    public class ClientDemo {
        public static void main(String[] args) throws UnknownHostException,
                IOException {
            Socket socket = new Socket("127.0.0.1", 55286);
            OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream());
            os.write("Santosh Karna");
            os.flush();
            socket.close();
        }
    }
    

    and
    ServerDemo.java

    public class ServerDemo {
        public static void main(String[] args) throws IOException {
            System.out.println("server is started");
            ServerSocket serverSocket= new ServerSocket(55286);
            System.out.println("server is waiting");
            Socket socket=serverSocket.accept();
            System.out.println("Client connected");
            BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String str=reader.readLine();
            System.out.println("Client data: "+str);
            socket.close();
            serverSocket.close();
    
        }
    }
    

    answered May 14, 2017 at 17:13

    Santosh Karna's user avatar

    Santosh KarnaSantosh Karna

    1191 gold badge7 silver badges12 bronze badges

    1

    I changed my DNS network and it fixed the problem

    answered Nov 23, 2019 at 9:51

    Elham Nikbakht's user avatar

    You probably didn’t initialize the server or client is trying to connect to wrong ip/port.

    answered Aug 10, 2020 at 16:21

    syclone's user avatar

    Change local host to your ip address

     localhost
     //to you local ip
     192.168.xxxx
    

    answered Apr 28, 2021 at 10:46

    Gabriel Rogath's user avatar

    Gabriel RogathGabriel Rogath

    6582 gold badges6 silver badges22 bronze badges

    There is a service called MySQL80 that should be running to connect to the database

    for windows you can access it by searching for services than look for MySQL80 service and make sure it is running

    answered Jul 16, 2021 at 19:50

    MonirRouissi's user avatar

    I saw the same error message «»java.net.ConnectException: Connection refused» in SQuirreLSQL when it was trying to connect to a postgresql database through an ssh tunnel.

    Example of opening tunel:
    enter image description here

    Example of error in Squirrel with Postgresql:

    enter image description here

    It was trying to connect to the wrong port. After entering the correct port, the process execution was successful.

    See more options to fix this error at: https://stackoverflow.com/a/6876306/5857023

    answered Jan 6, 2022 at 19:57

    Genivan's user avatar

    GenivanGenivan

    1612 gold badges3 silver badges10 bronze badges

    In my case, with server written in c# and client written in Java, I resolved it by specifying hostname as ‘localhost‘ in the server, and ‘[::1]‘ in the client. I don’t know why that is, but specifying ‘localhost’ in the client did not work.
    Supposedly these are synonyms in many ways, but apparently, not not a 100% match. Hope it helps someone avoid a headache.

    answered Aug 12, 2022 at 15:07

    AlexeiOst's user avatar

    AlexeiOstAlexeiOst

    5644 silver badges12 bronze badges

    For those who are experiencing the same problem and use Spring framework, I would suggest to check an http connection provider configuration. I mean RestTemplate, WebClient, etc.

    In my case there was a problem with configured RestTemplate (it’s just an example):

    public RestTemplate localRestTemplate() {
       Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", <some port>));
       SimpleClientHttpRequestFactory clientHttpReq = new SimpleClientHttpRequestFactory();
       clientHttpReq.setProxy(proxy);
       return new RestTemplate(clientHttpReq);
    }
    

    I just simplified configuration to:

    public RestTemplate restTemplate() {
       return new RestTemplate(new SimpleClientHttpRequestFactory());
    }
    

    And it started to work properly.

    answered Jan 24 at 17:45

    HereAndBeyond's user avatar

    It could be that there is a previous instance of the client still running and listening on port 5000.

    answered Jan 10, 2013 at 18:27

    Michael Munsey's user avatar

    Michael MunseyMichael Munsey

    3,6401 gold badge24 silver badges15 bronze badges

    2

    Метки:

    • java.net.connectexception connection timed out
    • no further information.
    • не могу подключиться
    • ошибка
    • помощь
    • проблема
    • решение
    1. Здравствуйте, вот просто накипело. ОЧЕНЬ ЧАСТО ВОЗНИКАЕТ java.net.connectexception connection timed out: no further information., по этому я решил сделать небольшой туториал, где опишу все известные мне причины возникновения данной ошибки и решение.

      java.net.connectexception connection timed out: no further information.
      И так, давайте сначала разберем основные причины:

      • Сервера к которому вы подключаетесь нет или он просто не доступен
      • Игра не может получить доступ к интернету

      Давайте рассмотрим пункт 1 подробнее и разделим его на несколько подпункутов

      • Сервера действительно нет. Его отключили или вы поключаетесь не к тому IP/Порту.
      • Сервер недоступен. У него нет доступа к интернету или его выключили.

      И тоже самое сделаем со вторым пунктом

      • У вас нет интернета.
      • У игры нет доступа к интернету.

      Разберем все 4 пункта:

      1. думаю тут все понятно.
      2. ну и тут тоже. (если сервер ваш, то смотрите пункт 4)
      3. не, ну проверьте интернет, а вдруг.
      4. а вот тут уже надо смотреть фаерволы и антивиры.

      Решение:

      • Открываем брэндмауэр windows и в списке приложений ставим все галочки на Java. Там может быть не 1, а несколько пунктов. Надо разрешить все.
      • Открываем антивирус, заносим minecraft в список исключений, разрешаем порт 25565, в конце концов отключаем его и пробуем обновиться.

      Если вы открыли мир для сети из меню:
      Данная ошибка обычно возникает в 3-х случаях

      • Не правильный IP:Порт
      • У игры нет доступа в интернет/Программа блокирует порт (Это разобрали, читайте решение ниже)
      • Обновите Java, часта данная ошибка возникает из-за разных версий

      И вообще, обновляйте Java, это решение, которое можно написать в каждый пункт.
      Скачать Java

      Для неопытных:
      Если вы создали сервер на своем ПК или открыли мир для сети в меню, то вам надо находиться в одной локальной сети. Если между вашими ПК нет соеденения по локальной сети, то используйте программы, которые создают такие (Например LogMeIn Hamachi или Evolve).
      Для того, что бы играть без соеденения по локальной сети, надо открыть порты. Я хз как это делается через торенты, port forwarding и т.п., тут просто используются дыры, которые не закрыл ваш интернет провайдер. По нормальному вам для открытия портов надо позвонить интернет провайдеру и спросить, будет ли он открывать порты, если да, то сделает ли он это бесплатно или надо заплатить, или может он эти порты и не закрывал.
      Проверить порт

    2. Быстрая раскрутка сервера Minecraft

    3. Писец ты нубяра. Сяпки, проорал в голос :D.

    4. Дополню. Если сервер пингуется и запускается без ошибок но подключится нельзя — у арендуемой VM машины могут быть заблокированы порты 8123 и 2565 (будет выскакивать та же ошибка timed out: no further information)

    Поделиться этой страницей

    Русское сообщество Bukkit

    Играя в Minecraft и вообще, пользуясь приложениями, написанными на Java Вы не раз могли столкнуться с ошибками (исключениями). В отличие от других языков программирования, Java жёстко заточена под использование ООП, потому при возникновении ошибки бросается исключение (объект содержащий сведения под ошибке). Его можно «поймать», дабы предпринять какие-то действия (допустим, вывести в лог). В случае майнкрафта, при возникновении исключения, создаётся краш-отчёт и работа игры завершается.

    Понять исключения достаточно просто и вам для этого не понадобится специальное ПО для отладки.

    2017-10-03_153645.png

    Полная печать исключения состоит из 3-х частей:

    1. Исключение — имя класса ошибки. Классам обычно дают понятные человеку имена, достаточно знаний английского, чтобы понять значение.
    2. Сообщение — содержит более детальное описание ошибки. Может отсутствовать.
    3. Стек вызова — отражает ход работы программы (снизу вверх). Данная информация больше полезна разработчику, дабы понять, где именно возникла ошибка. Обычному пользователю данная информация может помочь понять, с чем связана ошибка (по именам классов и вызываемым функциям — методам).

    Исключения могут иметь предков, что присутствует в данном примере (после «Caused by» идёт печать исключения-предка). Если вам не понятно исключение, возможно, стоит рассмотреть его предков — они могут содержать более понятное сообщение.

    В данной теме я опишу наиболее часто встречающиеся ошибки, а также, какие действия следует или вовсе не следует предпринимать. Причин у ошибок множество и это не всегда повреждённые файлы игры (чего быть в принципе не может, поскольку лаунчер проверяет файлы игры).

    При возникновении ошибок не спешите бежать переустанавливать Java и игру! Java — стабильный продукт. В большинстве случаев, ошибки возникают из-за неправильной настройки ОС; ошибок сети; неправильных драйверов.

    org.lwjgl.LWJGLException: Pixel format not accelerated
    Недоступно аппаратное ускорение графики. Описание ошибки (англ.)

    Решение: Установите последнюю версию драйвера видеокарты.

    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation/building failed
    Не удаётся установить защищённое соединение из-за невозможности проверки SSL сертификата.

    Что можно сделать:

    • Эта ошибка может возникнуть из-за использования слишком старой версии Java. Рекомендуется регулярно обновлять ПО, чтобы иметь актуальный список корневых сертификатов.
    • Виновником может быть антивирус, пытающийся «подсунуть» свой сертификат с целью прослушивания трафика. Настоятельно рекомендуется отключить в антивирусе проверку защищённых соединений (HTTPS/SSL/TLS) — это значительно снижает безопасность защищённых соединений и вызывает проблемы в работе приложений, использующие их.

    java.net.SocketTimeOutException: Read timed out
    Ошибка сети «время ожидания истекло». Здесь сложно установить виновника: проблема может быть как на стороне сервера, вашего провайдера или вызвана антивирусом.

    Что можно сделать:

    • Отключите антивирус и попробуйте выполнить запрос снова.
    • Используйте другое подключение к интернету (другой провайдер; мобильный интернет; VPN; Wi-Fi соседей).
    • Используйте VPN для обхода блокировки (цензуры) со стороны вашего интернет-провайдера.

    java.net.ConnectException: Connection timed out: connect
    Ошибка сети — не удалось установить соединение с хостом. Обычно виновником данной ошибки является Firewall (брандмауэр) или отсутствие интернета.

    Что можно сделать:

    • Проверьте наличие подключения к интернету.
    • Временно отключите антивирус и Firewall.

    java.net.SocketException: Connection reset / Удаленный хост принудительно разорвал существующее подключение
    Ошибка сети «соединение сброшено». Как и в предыдущей ошибке, проблема связана с «плохим» интернетом, либо проблемами на стороне сервера (в этом случае ошибка будет у всех). Чаще всего возникает у пользователей мобильного интернета (USB-модем). От вас никаких действий предпринимать не требуется, кроме как найти «другой интернет» или использовать VPN для обхода фильтра сайтов.

    java.lang.ClassCastException: XXX cannot be cast to YYY
    Ошибка в логике программы: попытка привести объект к классу, экземпляром коего объект не является.

    Решение: Сообщите о проблеме разработчику программы, приложив лог ошибки.

    java.io.IOException: Server returned HTTP response code: 000 for URL
    Проблема на стороне веб-сервера. Стандартная библиотека Java выбрасывает исключение, если веб-сервер выдаёт, например, страницу «404 Not Found».

    Решение: Сообщите о проблеме владельцу веб-сервера, URL которого указан в тексте ошибки.

    java.lang.UnsatisfiedLinkError: Can’t load library:
    Не удалось загрузить нативную библиотеку (скорее всего, отсутствует файл по указанному пути).

    Что можно сделать:

    • Чаще всего ошибка возникает из-за отсутствия библиотек LWJGL. Почему их файлы пропадают, пока остаётся загадкой. Если пути вы видите «.redserver/natives/2.9.1/lwjgl.dll», значит надо удалить папку natives, находящуюся в .redserver, чтобы лаунчер их скачал заново.
      Неактуально: С версии 3.2 лаунчер проверяет наличие всех файлов и автоматически, при необходимости, перекачивает их.

    java.lang.RuntimeException: Unknown character in
    Синтаксическая ошибка в конфигурационном файле мода.

    Что можно сделать:

    • Удалите указанный в ошибке файл. Мод создаст новый с настройками по умолчанию.
    • Если вам сложно удалить файл, можно сделать сброс конфигов через лаунчер. Нажмите в лаунчере на многоточие на кнопке «Играть»; выберите в меню пункт «Очистка клиента»; установите флажок возле «Сбросить конфигурацию» и запустите очистку.
    • Выполните проверку диска на наличие ошибок. Испорченные файлы могут быть признаком неисправности диска.

    java.lang.NullPointerException (NPE)
    Ошибка в логике программы: попытка вызвать нестатичный метод, обратиться к полю несуществующего объекта — null.

    Решение: Сообщите о проблеме разработчику программы, приложив лог ошибки.

    java.net.UnknownHostException
    Ошибка сети: не удаётся определить IP-адрес доменного имени (в общем, проблемы с DNS).

    Что можно сделать:

    • Иногда ошибка может возникать, если вы не подключены к интернету, либо же произошёл разрыв интернет-соединения. Обычно исчезает сама через небольшой промежуток времени после возобновления соединения. Если ошибка не исчезла — может помочь перезагрузка компьютера (сбрасывает кеш DNS).
    • Доступ к ресурсу заблокирован вашим провайдером. Сейчас данная проблема актуальна для украинских пользователей: используемый нами Яндекс.DNS заблокирован в этой стране. Читайте, как обойти блокировку DNS.

    java.io.EOFException: Unexpected end of ZLIB input stream
    Неожиданный конец файла. В данном случае — ZIP-архива. Возникает например, когда вы пытаетесь распаковать недокачанный архив.

    java.net.SocketException: Address family not supported by protocol family: connect
    Проблема возникает из-за неправильной настройки протокола IPv6. Если таковой не поддерживается вашим интернет-провайдером, его поддержку следует отключить.

    image.png

    java.lang.OutOfMemoryError
    А вот это как раз «любимая» ошибка про нехватку ОЗУ. Не стоит сразу спешить выставлять память в лаунчере на максимум, потому что дальнейшие действия зависят от сообщения к ошибке:

    • Unable to create new native thread / Metaspace — в вашей системе закончились ресурсы (ОЗУ). Решается только путём завершения всех лишних программ, либо апгрейдом ПК (больше ОЗУ — больше программ можно запустить). Не забывайте, что следует использовать 64-разрядную систему.
    • Java heap space — нехватка размера heap области памяти. Увеличьте лимит памяти в настройках лаунчера.

    How to solve java.net.ConnectException: Connection refused

    Yoodley is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

    The simplest remedy is to figure out what is causing java.net.ConnectException: Connection refused. What is most significant in this case is the approach taken in determining the correct cause and solution. Here are some suggestions that may assist you in determining the root cause.

    • First, ping the destination host; if the host is ping-able, this indicates that both the client and server machines are connected to the network.
    • Use telnet to establish a connection to the server’s host and port. Inability to connect indicates that there is a problem with your client software code. Additionally, by examining the telnet output, you will be able to determine whether the server is functioning or not, as well as whether the server is severing the connection from the client.

    Reasons For The Error: java.net.ConnectException: Connection refused

    Connection rejected is a clear example of a client attempting to establish a connection on a TCP port but failing. Here are some of the possible causes of the error that could be encountered:

    Reason 1: Client and Server, either or both of them are not in the network.

    The fact that client and server are not linked to a LAN, the internet, or any other network is a possibility, and in that case, Java will throw an error message.This error message is the same one we are dealing with: java.net.ConnectException: Connection refused.

    Reason 2: Server is not running

    The second most frequently encountered issue is that the server is not up and operating. In that scenario, you will additionally receive java.net. ConnectException: Connection refused error.

    What we don’t like about it is that no matter what the reason for the issue is, it always produces the same error message.

    Furthermore, you can use the following networking commands, such as ping to determine whether the server is up and running and listening on the specified port.

    Reason 3: The server is running but not listening on the port, a client is trying to connect.

    This is yet another typical reason for “java.net.ConnectException: Connection refused  “, in which the server is up and running but is listening on a different port than usual. It’s difficult to figure out this case unless you sit down and think about it, then you can verify the settings. If you are working on a large project with a hierarchical configuration file, it is possible that either the default configuration or or another setting is taking precedence over your current configuration.

    Reason 4: Firewall is not permitted for host-port combination

    Firewalls are used to secure almost every corporate network today. It is necessary to raise firewall requests from both sides when connecting to another company’s network, for example, when starting a FIX session to the broker in an Electronic Trading System, in order to verify that the IP address and port number of the other company’s network are permitted. If the firewall is not allowing the connection,  you will also receive the same java.net.ConnectException: Connection refused exception in Java application.

    Reason 5: Host Port combination is incorrect.

    This could be yet another explanation for the existence of java.net.Connection refused.  You should consider the possibility that either you are supplying an invalid host port combination or that a previously used host port combination has been modified on the server’s end. Check for the most recent configuration on both the client and server sides to avoid connection denied exceptions from occurring.

    Reason 6: Incorrect protocol in Connection String

    TCP is the underlying protocol for several high-level protocols, including HTTP, RMI, and others. TCP is a transmission control protocol. Ensure that you are giving the correct connection string to the server, which begins with the protocol that the server expects, for example, if the server has exposed its service via RMI, the connection string should begin with rmi:/

    How to fix java.lang.OutOfMemoryError: Java heap space?

    An easy technique to resolve OutOfMemoryError in Java is to increase the maximum heap size using JVM options “-Xmx512M”, which will resolve your OutOfMemoryError quickly.

    Alternative Method:

    The second method to resolve OutOfMemoryError in Java is more difficult and occurs when you don’t have much memory and even after increasing the maximum heap size you still get java.lang.OutOfMemoryError; in this situation, you should definitely profile your programme and look for any memory leak.

    You may also check your heap dump with Eclipse Memory Analyzer or any profiler such as Netbeans or JProbe. This is a difficult solution that will take some time to investigate and detect memory leaks.

    How to solve java.lang.OutOfMemoryError: PermGen space?

    As stated in the above paragraph, the OutOfMemory issue in Java occurs when the heap’s Permanent generation is depleted. To resolve this OutOfMemoryError in Java, use the JVM option “-XX: MaxPermSize” to raise the heap size of the Perm area.

    You can also provide the initial size of Perm Space with “-XX: PermSize,” and by retaining both the initial and maximum Perm Space, you can avoid certain entire garbage collection that may occur when Perm Space is resized.

    java.lang.OutOfMemoryError in Java can be tricky at times, and in those circumstances, profiling is the best answer. While you have the option to increase heap size in Java, it is advised that you follow memory management techniques while coding and add null to any unnecessary references.

    Read More

    iFrame (Site name) Connection Refused

    Перейти к содержанию

    При попытке подключения к серверу «Майнкрафт» пользователь может столкнуться с сообщением «Java.net.ConnectException: Connection timed out: no further information». Появление данного сообщения обычно сигнализирует о возникновении различного рода сетевых проблем при получении доступа к игровому серверу, из-за чего желание пользователя насладиться игровыми мирами «Майнкрафт» остаётся нереализованным. Ниже я разберу суть данной дисфункции, опишу её причины, а также поясню, как исправить ошибку Java.net.ConnEctexception на вашем ПК.

    Сообщение Java.net.ConnectException

    Содержание

    1. Connection timed out: no further information – особенности дисфункции
    2. Как исправить «Java.net.ConnectException: Connection timed out»
    3. Заключение

    Connection timed out: no further information – особенности дисфункции

    В переводе текст данного сообщения выглядит примерно как «Сетевой сбой Java. Время соединения истекло: дальнейшая информация отсутствует».

    Указанная ошибка Java.net.ConnectException обычно возникает во время подключения к серверу игры «Майнкрафт», но также фиксировались спорадические случаи появления данной ошибки при работе других продуктов, использующих «Java» (к примеру, на «Azure notification hub»).

    Появление проблемы «Java.net.ConnectException: Connection timed out: no further information» имеет следующие причины:

    • Пользователь использует нестабильное сетевое соединение с медленным интернетом;
    • На ПК пользователя установлена устаревшая версия «Java»;
    • Пользователь пользуется устаревшей версией «Майнкрафт»;
    • Наблюдаются сбои в работе игрового сервера, к которому пробует подключиться пользователь (ресурс не доступен, проходят технические работы и др.);
    • Антивирус или брандмауэр блокирует подключения к игровому серверу;
    • Пользователь использует динамический IP;
    • Пользовательский роутер работает некорректно.

    Как исправить «Java.net.ConnectException: Connection timed out»

    Существуют несколько способов избавиться от ошибки Java.net.ConnectException. Рассмотрим их по порядку:

    • Перезагрузите ваш PC. В некоторых случаях данный простой метод позволял решить ошибку java.net.connectexception connection refused;
    • Установите на ПК свежую версию «Java». Довольно частой причиной рассматриваемой проблемы является устаревшая версия «Java» на пользовательском ПК. Перейдите в Панель управления, затем в «Программы», там найдите «Java» и кликните на неё. После появления окна её настроек перейдите на вкладку «Update», нажмите там на кнопку «Update Now», и установите в системе требуемые обновления.

    Данную процедуру необходимо провести как на вашей машине, так и на машине того пользователя, с которым вы собираетесь играть в «Майнкрафт» по сети;

    Кнопка

    • Внесите «Майнкрафт» в исключения брандмауэра и антивируса на вашем ПК. Запустите Панель управления, перейдите в «Система и безопасность», там найдите «Брандмауэр Виндовс» и кликните на него. В открывшемся окне настроек брандмауэра слева сверху выберите опцию «Разрешения взаимодействия…».Опция разрешения взаимодействияВ открывшемся окне разрешённых для внешнего подключения программ найдите программы с упоминанием «Java», и поставьте им галочки для разрешения подключения (поможет кнопка «Изменить параметры»). Нажимаем на «Ок» для сохранения результата, перезагружаемся и пробуем подключиться к серверу. С антивирусом необходимо проделать аналогичные операции, внеся «Java» и «Майнкрафт» в его исключения;
    • Попробуйте альтернативный сервер. Если подключения к конкретному серверу невозможно, тогда вполне вероятно, что у него наблюдаются временные проблемы в работе. Рекомендую попробовать альтернативный сервер, или подождать некоторое время, пока работоспособность начального сервера восстановиться;
    • Создайте сервер на другой машине. Если вы создаёте сервер, к которому подключается другой знакомый вам пользователь, тогда рекомендуется поменять базовый компьютер для создания сервера. То есть сервер должен создать уже другой пользователь, а вы подключитесь к нему. Часто это позволяло решить проблему net.ConnectException на пользовательском компьютере;
    • Используйте статистический IP-адрес. Если у вас есть возможность, рекомендуется использовать официальный (белый) IP-адрес, полученный через провайдера (обычно данная услуга имеет платный характер);
    • Установите на ваш ПК (гаджет) свежую версию «Майнкрафт». Обычно необходимо, чтобы версии игры на сервере и на вашем ПК (гаджете) соответствовали друг другу; Картинка MINECRAFT
      Установите самую свежую версию программы
    • Избавьтесь от имеющихся модов к игре. Если вы используете какие-либо моды «Майнкрафт», рекомендуется удалить их, оставив само тело игры;
    • Перезагрузите ваш роутер. Отключите ваш роутер, подождите полминуты, а затем включите его обратно;
    • Обратитесь за консультацией к провайдеру. По различным причинам некоторые провайдеры блокируют доступ к некоторым серверам. Узнайте, не ваш ли это случай, и не является ли ваш провайдер причиной возникновения данной проблемы.

    Заключение

    Наиболее распространёнными причинами ошибки «Java.net.ConnectException: Connection timed out: no further information» является устаревание пользовательской версии «Java» и блокировка брандмауэром подключения к нужному игровому серверу. Решением проблемы станет выполнение перечисленных выше советов, это позволит исправить ошибку Java.net.ConnectException на вашем ПК.

    Опубликовано 21.03.2018 Обновлено 03.12.2020

    Improve Article

    Save Article

    Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    java.net.ConnectException: Connection refused: connect is the most frequent kind of occurring networking exception in Java whenever the software is in client-server architecture and trying to make a TCP connection from the client to the server. We need to handle the exception carefully in order to fulfill the communication problem. First, let us see the possible reasons for the occurrence of java.net.ConnectException: Connection refused.

    1. As client and server involved, both should be in a network like LAN or internet. If it is not present, it will throw an exception on the client-side.
    2. If the server is not running. Usually ports like 8080, (for tomcat), 3000 or 4200 (for react/angular), 3306(MySQL), 27017(MongoDB) or occupied by some other agents or totally down i.e. instance not started.
    3. Sometimes a server may be running but not listening on port because of some overridden settings etc.
    4. Usually, for security reasons, the Firewall will be there, and if it is disallowing the communication.
    5. By mistake, the wrong port is mentioned in the port or the random port generation number given.
    6. Connection string information wrong. For example:

    Connection conn = DriverManager.getConnection(“jdbc:mysql://localhost/:3306<dbname>?” + “user=<username>&password=<password>”);

    Implementation: Here we are using MySQL database connectivity and connection info should be of this format. Now let us see the ways to fixing the ways of java.net.ConnectException: Connection refused. Ping the destination host by using the commands as shown below:

    ping <hostname> - to test
    
    ipconfig(for windows)/ifconfig(linux) - to get network configuration
    
    netstat - statistical report

    nslookup - DNS lookup name

    There are tools like “Putty” are available to communicate, and it is a free implementation of Telnet and SSH for Windows and Unix.

    Example 1: 

    Java

    import java.io;

    import java.net.*;

    import java.util.*;

    public class GFG {

        public static void main(String[] args)

        {

            String hostname = "127.0.0.1";

            int port = 80;

            try (Socket socket = new Socket(hostname, port)) {

                InputStream inputStream

                    = socket.getInputStream();

                InputStreamReader inputStreamReader

                    = new InputStreamReader(inputStream);

                int data;

                StringBuilder outputString

                    = new StringBuilder();

                while ((data = inputStreamReader.read())

                       != -1) {

                    outputString.append((char)data);

                }

            }

            catch (IOException ex) {

                System.out.println(

                    "Connection Refused Exception as the given hostname and port are invalid : "

                    + ex.getMessage());

            }

        }

    }

    Output:

    Example 2: MySQL connectivity Check

    Java

    import java.io.*;

    import java.util.*;

    import java.sql.*;

    try {

        Connection con = null;

        String driver = "com.mysql.jdbc.Driver";

        String IPADDRESS = "localhost"

            String url1

        String db = "<your dbname>";

        String dbUser = "<username>";

        String dbPasswd = "<password>";

        Class.forName(driver).newInstance();

        con = DriverManager.getConnection(url1 + db, dbUser,

                                          dbPasswd);

        System.out.println("Database Connection Established");

    }

    catch (IOException ex) {

        System.out.println(

            "Connection Refused Exception as the given hostname and port are invalid : "

            + ex.getMessage());

    }

    Similarly, for other DB, we need to specify the correct port number i.e. 27017 for MongoDB be it in case of SSL (Secure socket layer) is there, prior checks of Firewall need to be checked and hence via coding we can suggest the solutions to overcome the exception 

    Conclusion: As readymade commands like ping, telnet, etc are available and tools like putty are available, we can check the connectivity information and overcome the exception.

    Last Updated :
    04 Feb, 2022

    Like Article

    Save Article

    I’m trying to implement a TCP connection, everything works fine from the server’s side but when I run the client program (from client computer) I get the following error:

    java.net.ConnectException: Connection refused
            at java.net.PlainSocketImpl.socketConnect(Native Method)
            at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
            at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
            at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
            at java.net.Socket.connect(Socket.java:529)
            at java.net.Socket.connect(Socket.java:478)
            at java.net.Socket.<init>(Socket.java:375)
            at java.net.Socket.<init>(Socket.java:189)
            at TCPClient.main(TCPClient.java:13)
    

    I tried changing the socket number in case it was in use but to no avail, does anyone know what is causing this error & how to fix it.

    The Server Code:

    //TCPServer.java
    
    import java.io.*;
    import java.net.*;
    
    class TCPServer {
        public static void main(String argv[]) throws Exception {
            String fromclient;
            String toclient;
    
            ServerSocket Server = new ServerSocket(5000);
    
            System.out.println("TCPServer Waiting for client on port 5000");
    
            while (true) {
                Socket connected = Server.accept();
                System.out.println(" THE CLIENT" + " " + connected.getInetAddress()
                        + ":" + connected.getPort() + " IS CONNECTED ");
    
                BufferedReader inFromUser = new BufferedReader(
                        new InputStreamReader(System.in));
    
                BufferedReader inFromClient = new BufferedReader(
                        new InputStreamReader(connected.getInputStream()));
    
                PrintWriter outToClient = new PrintWriter(
                        connected.getOutputStream(), true);
    
                while (true) {
    
                    System.out.println("SEND(Type Q or q to Quit):");
                    toclient = inFromUser.readLine();
    
                    if (toclient.equals("q") || toclient.equals("Q")) {
                        outToClient.println(toclient);
                        connected.close();
                        break;
                    } else {
                        outToClient.println(toclient);
                    }
    
                    fromclient = inFromClient.readLine();
    
                    if (fromclient.equals("q") || fromclient.equals("Q")) {
                        connected.close();
                        break;
                    } else {
                        System.out.println("RECIEVED:" + fromclient);
                    }
    
                }
    
            }
        }
    }
    

    The Client Code:

    //TCPClient.java
    
    import java.io.*;
    import java.net.*;
    
    class TCPClient {
        public static void main(String argv[]) throws Exception {
            String FromServer;
            String ToServer;
    
            Socket clientSocket = new Socket("localhost", 5000);
    
            BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
                    System.in));
    
            PrintWriter outToServer = new PrintWriter(
                    clientSocket.getOutputStream(), true);
    
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
                    clientSocket.getInputStream()));
    
            while (true) {
    
                FromServer = inFromServer.readLine();
    
                if (FromServer.equals("q") || FromServer.equals("Q")) {
                    clientSocket.close();
                    break;
                } else {
                    System.out.println("RECIEVED:" + FromServer);
                    System.out.println("SEND(Type Q or q to Quit):");
    
                    ToServer = inFromUser.readLine();
    
                    if (ToServer.equals("Q") || ToServer.equals("q")) {
                        outToServer.println(ToServer);
                        clientSocket.close();
                        break;
                    } else {
                        outToServer.println(ToServer);
                    }
                }
            }
        }
    }
    

    Ashish Aggarwal's user avatar

    asked Jul 29, 2011 at 16:37

    Samantha Catania's user avatar

    Samantha CataniaSamantha Catania

    5,0765 gold badges38 silver badges69 bronze badges

    8

    This exception means that there is no service listening on the IP/port you are trying to connect to:

    • You are trying to connect to the wrong IP/Host or port.
    • You have not started your server.
    • Your server is not listening for connections.
    • On Windows servers, the listen backlog queue is full.

    tk_'s user avatar

    tk_

    16.3k8 gold badges80 silver badges90 bronze badges

    answered Jul 29, 2011 at 16:41

    Collin Price's user avatar

    Collin PriceCollin Price

    5,6103 gold badges33 silver badges35 bronze badges

    9

    I would check:

    • Host name and port you’re trying to connect to
    • The server side has managed to start listening correctly
    • There’s no firewall blocking the connection

    The simplest starting point is probably to try to connect manually from the client machine using telnet or Putty. If that succeeds, then the problem is in your client code. If it doesn’t, you need to work out why it hasn’t. Wireshark may help you on this front.

    answered Jul 29, 2011 at 16:39

    Jon Skeet's user avatar

    Jon SkeetJon Skeet

    1.4m862 gold badges9104 silver badges9178 bronze badges

    4

    You have to connect your client socket to the remote ServerSocket. Instead of

    Socket clientSocket = new Socket("localhost", 5000);

    do

    Socket clientSocket = new Socket(serverName, 5000);

    The client must connect to serverName which should match the name or IP of the box on which your ServerSocket was instantiated (the name must be reachable from the client machine). BTW: It’s not the name that is important, it’s all about IP addresses…

    user207421's user avatar

    user207421

    305k43 gold badges304 silver badges480 bronze badges

    answered Jul 29, 2011 at 17:21

    home's user avatar

    6

    I had the same problem, but running the Server before running the Client fixed it.

    answered Jul 25, 2012 at 18:09

    Dao Lam's user avatar

    Dao LamDao Lam

    2,83711 gold badges37 silver badges44 bronze badges

    3

    One point that I would like to add to the answers above is my experience

    «I hosted on my server on localhost and was trying to connect to it through an android emulator by specifying proper URL like http://localhost/my_api/login.php . And I was getting connection refused error«

    Point to note — When I just went to browser on the PC and use the same URL (http://localhost/my_api/login.php) I was getting correct response

    so the Problem in my case was the term localhost which I replaced with the IP for my server (as your server is hosted on your machine) which made it reachable from my emulator on the same PC.


    To get IP for your local machine, you can use ipconfig command on cmd
    you will get IPv4 something like 192.68.xx.yy
    Voila ..that’s your machine’s IP where you have your server hosted.
    use it then instead of localhost

    http://192.168.72.66/my_api/login.php


    Note — you won’t be able to reach this private IP from any node outside this computer. (In case you need ,you can use Ngnix for that)

    answered Feb 26, 2018 at 16:50

    eRaisedToX's user avatar

    eRaisedToXeRaisedToX

    3,1912 gold badges22 silver badges28 bronze badges

    0

    I had the same problem with Mqtt broker called vernemq.but solved it by adding the following.

    1. $ sudo vmq-admin listener show

    to show the list o allowed ips and ports for vernemq

    1. $ sudo vmq-admin listener start port=1885 -a 0.0.0.0 --mountpoint /appname --nr_of_acceptors=10 --max_connections=20000

    to add any ip and your new port. now u should be able to connect without any problem.

    Hope it solves your problem.
    enter image description here

    answered Apr 5, 2016 at 7:58

    MrOnyancha's user avatar

    MrOnyanchaMrOnyancha

    6055 silver badges28 bronze badges

    1

    Hope my experience may be useful to someone. I faced the problem with the same exception stack trace and I couldn’t understand what the issue was. The Database server which I was trying to connect was running and the port was open and was accepting connections.

    The issue was with internet connection. The internet connection that I was using was not allowed to connect to the corresponding server. When I changed the connection details, the issue got resolved.

    answered Nov 17, 2014 at 12:01

    phoenix's user avatar

    phoenixphoenix

    9853 gold badges17 silver badges38 bronze badges

    In my case, I gave the socket the name of the server (in my case «raspberrypi»), and instead an IPv4 address made it, or to specify, IPv6 was broken (the name resolved to an IPv6)

    answered Dec 21, 2016 at 18:20

    Zhyano's user avatar

    ZhyanoZhyano

    3991 gold badge3 silver badges13 bronze badges

    In my case, I had to put a check mark near Expose daemon on tcp://localhost:2375 without TLS in docker setting (on the right side of the task bar, right click on docker, select setting)

    answered Aug 23, 2017 at 13:42

    user1419243's user avatar

    user1419243user1419243

    1,6553 gold badges18 silver badges33 bronze badges

    i got this error because I closed ServerSocket inside a for loop that try to accept number of clients inside it (I did not finished accepting all clints)

    so be careful where to close your Socket

    user207421's user avatar

    user207421

    305k43 gold badges304 silver badges480 bronze badges

    answered May 21, 2016 at 21:07

    Basheer AL-MOMANI's user avatar

    I changed my DNS network and it fixed the problem

    answered Nov 23, 2019 at 9:51

    Elham Nikbakht's user avatar

    I saw the same error message «»java.net.ConnectException: Connection refused» in SQuirreLSQL when it was trying to connect to a postgresql database through an ssh tunnel.

    Example of opening tunel:
    enter image description here

    Example of error in Squirrel with Postgresql:

    enter image description here

    It was trying to connect to the wrong port. After entering the correct port, the process execution was successful.

    See more options to fix this error at: https://stackoverflow.com/a/6876306/5857023

    answered Jan 6, 2022 at 19:57

    Genivan's user avatar

    GenivanGenivan

    1712 gold badges3 silver badges10 bronze badges

    For those who are experiencing the same problem and use Spring framework, I would suggest to check an http connection provider configuration. I mean RestTemplate, WebClient, etc.

    In my case there was a problem with configured RestTemplate (it’s just an example):

    public RestTemplate localRestTemplate() {
       Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", <some port>));
       SimpleClientHttpRequestFactory clientHttpReq = new SimpleClientHttpRequestFactory();
       clientHttpReq.setProxy(proxy);
       return new RestTemplate(clientHttpReq);
    }
    

    I just simplified configuration to:

    public RestTemplate restTemplate() {
       return new RestTemplate(new SimpleClientHttpRequestFactory());
    }
    

    And it started to work properly.

    answered Jan 24 at 17:45

    HereAndBeyond's user avatar

    I had same problem and the problem was that I was not closing socket object.After using socket.close(); problem solved.
    This code works for me.

    ClientDemo.java

    public class ClientDemo {
        public static void main(String[] args) throws UnknownHostException,
                IOException {
            Socket socket = new Socket("127.0.0.1", 55286);
            OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream());
            os.write("Santosh Karna");
            os.flush();
            socket.close();
        }
    }
    

    and
    ServerDemo.java

    public class ServerDemo {
        public static void main(String[] args) throws IOException {
            System.out.println("server is started");
            ServerSocket serverSocket= new ServerSocket(55286);
            System.out.println("server is waiting");
            Socket socket=serverSocket.accept();
            System.out.println("Client connected");
            BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String str=reader.readLine();
            System.out.println("Client data: "+str);
            socket.close();
            serverSocket.close();
    
        }
    }
    

    answered May 14, 2017 at 17:13

    Santosh Karna's user avatar

    Santosh KarnaSantosh Karna

    1191 gold badge3 silver badges12 bronze badges

    1

    You probably didn’t initialize the server or client is trying to connect to wrong ip/port.

    answered Aug 10, 2020 at 16:21

    syclone's user avatar

    Change local host to your ip address

     localhost
     //to you local ip
     192.168.xxxx
    

    answered Apr 28, 2021 at 10:46

    Gabriel Rogath's user avatar

    Gabriel RogathGabriel Rogath

    6902 gold badges8 silver badges23 bronze badges

    In my case, with server written in c# and client written in Java, I resolved it by specifying hostname as ‘localhost‘ in the server, and ‘[::1]‘ in the client. I don’t know why that is, but specifying ‘localhost’ in the client did not work.
    Supposedly these are synonyms in many ways, but apparently, not not a 100% match. Hope it helps someone avoid a headache.

    answered Aug 12, 2022 at 15:07

    AlexeiOst's user avatar

    AlexeiOstAlexeiOst

    5644 silver badges13 bronze badges

    If you use intellij and you encounter the same error, check if you don’t have a method breakpoint enabled somewhere. It worked for me :)

    answered Jun 13 at 8:20

    Abdelilah Razzouk's user avatar

    There is a service called MySQL80 that should be running to connect to the database

    for windows you can access it by searching for services than look for MySQL80 service and make sure it is running

    answered Jul 16, 2021 at 19:50

    MonirRouissi's user avatar

    It could be that there is a previous instance of the client still running and listening on port 5000.

    answered Jan 10, 2013 at 18:27

    Michael Munsey's user avatar

    Michael MunseyMichael Munsey

    3,7301 gold badge25 silver badges15 bronze badges

    2

    Ошибка java.net.ConnectException: Connection refused является одним из самых распространенных сетевых исключений в Java. Эта ошибка возникает, когда вы работаете с архитектурой клиент-сервер и пытаетесь установить TCP-соединение от клиента к серверу.

    Соединение также происходит в случае RMI (удаленного вызова метода), потому что RMI также использует протокол TCP-IP. При написании кода клиентского сокета на Java вы всегда должны обеспечивать правильную обработку этого исключения.

    В этом руководстве по Java вы узнаете, почему возникает исключение при отказе в соединении и как решить проблему.

    Причины

    ошибка java.net.ConnectException: Connection refused

    Отказ в соединении – это явный случай, когда клиент пытается подключиться через порт TCP, но не может это сделать. Вот некоторые из возможных причин, почему это происходит:

    1. Клиент и Сервер, один или оба из них не находятся в сети.

    Да, возможно, что они не подключены к локальной сети, Интернету или любой другой сети.

    1. Сервер не работает.

    Вторая наиболее распространенная причина – сервер не работает. Вы можете использовать следующие сетевые команды, например, ping, чтобы проверить, работает ли сервер.

    1. Сервер работает, но не видит порт, к которому клиент пытается подключиться.

    Это еще одна распространенная причина возникновения «java.net.ConnectException: соединение отклонено», когда сервер работает, но видит другой порт. Трудно разобраться в этом случае, пока вы не проверите конфигурацию.

    1. Брандмауэр запрещает комбинацию хост-порт.

    Почти каждая корпоративная сеть защищена. Если вы подключаетесь к сети других компаний, вам нужно убедиться, что они разрешают друг другу IP-адрес и номер порта.

    1. Неверная комбинация хост-портов.

    Проверьте последнюю конфигурацию на стороне клиента и сервера, чтобы избежать исключения отказа в соединении.

    1. Неверный протокол в строке подключения.

    TCP является базовым протоколом для многих высокоуровневых протоколов, включая HTTP, RMI и другие. Нужно убедиться, что вы передаете правильный протокол, какой сервер ожидает.

    Если вам интересно узнать больше об этом, то изучите книгу по сетевым технологиям, такую ​​как Java Network Programming (4-е дополнение), написанную Гарольдом Эллиоттом Расти.

    Java Network Programming

    Простое решение состоит в том, чтобы сначала выяснить фактическую причину исключения. Здесь важнее всего подход к поиску правильной причины и решения. Как только вы узнаете реальную причину, вам, возможно, даже не потребуется вносить какие-либо существенные изменения.

    Вот несколько советов, которые могут помочь исправить ошибку java.net.ConnectException: Connection refused:

    1. Сначала попытайтесь пропинговать целевой хост, если хост способен пинговать, это означает, что клиент и сервер находятся в сети.
    2. Попробуйте подключиться к хосту и порту сервера, используя telnet. Если вы можете подключиться, значит что-то не так с вашим клиентским кодом. Кроме того, наблюдая за выводом telnet, вы узнаете, работает ли сервер или нет, или сервер отключает соединение.

    

  • Ошибка java lang securityexception permission denial
  • Ошибка java lang runtimeexception java lang nullpointerexception
  • Ошибка java lang reflect undeclaredthrowableexception
  • Ошибка java lang nullpointerexception на андроид
  • Ошибка java io ioexception stalcraft