java net connectexception connection refused connect что делать

java.сеть.ConnectException: соединение отказано

Я пытаюсь реализовать TCP-соединение, все работает нормально со стороны сервера, но когда я запускаю клиентскую программу (с клиентского компьютера), я получаю следующую ошибку:

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

14 ответов

это исключение означает, что служба не прослушивает IP / порт, к которому вы пытаетесь подключиться:

самой простой отправной точкой, вероятно, является попытка подключиться вручную с клиентской машины с помощью telnet или Putty. Если это удастся, проблема будет в вашем клиентском коде. Если это не так, вам нужно работать почему это не так. Wireshark может помочь вам на этом фронте.

вы должны подключить клиентский сокет к удаленному ServerSocket. Вместо

Socket clientSocket = new Socket(«localhost», 5000);

Socket clientSocket = new Socket(serverName, 5000);

клиент должен подключиться к имя_сервера который должен соответствовать имени или IP коробки, на которой ваш ServerSocket был создан экземпляр (имя должно быть доступно с клиентского компьютера). Кстати: это не имя, которое важно, это все об IP-адресах.

у меня была такая же проблема с брокером Mqtt под названием vernemq.но решил его, добавив следующее.

чтобы показать список o разрешенные ips и порты для vernemq

добавить любой ip и ваш новый порт. теперь вы должны быть в состоянии подключиться без каких-либо проблем.

надеюсь, это решит вашу проблему. java net connectexception connection refused connect что делать. Смотреть фото java net connectexception connection refused connect что делать. Смотреть картинку java net connectexception connection refused connect что делать. Картинка про java net connectexception connection refused connect что делать. Фото java net connectexception connection refused connect что делать

У меня была та же проблема, но запуск сервера перед запуском клиента исправил ее.

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

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

Я получил эту ошибку, потому что I closed ServerSocket inside a for loop которые пытаются принять количество клиентов внутри него (я не закончил принимать все клинты)

поэтому будьте осторожны, где закрыть сокет

в моем случае я дал сокету имя сервера (в моем случае «raspberrypi»), и вместо этого IPv4-адрес сделал это, или указать, IPv6 был сломан (имя разрешено на IPv6)

в моем случае я должен был поставить галочку рядом Expose daemon on tcp://localhost:2375 without TLS на docker настройка (в правой части панели задач, щелкните правой кнопкой мыши на docker выберите setting )

номер порта всегда отличается на обоих концах

у меня была такая же проблема и проблема в том, что я не закрывал объект сокета.После использования сокета.закрыть(); проблема решена. Этот код работает для меня.

один момент, который я хотел бы добавить к выше ответы мой опыт

Итак, проблема в моем случае был срок localhost который Я заменил на IP для моего сервера (поскольку ваш сервер размещен на вашем компьютере), который сделал его доступным из моего эмулятора на том же ПК.

Источник

How To Fix java.net.ConnectException: Connection refused in Java

java net connectexception connection refused connect что делать. Смотреть фото java net connectexception connection refused connect что делать. Смотреть картинку java net connectexception connection refused connect что делать. Картинка про java net connectexception connection refused connect что делать. Фото java net connectexception connection refused connect что делать

java.net.ConnectException: Connection refused is a common exception if you are dealing with network operations in Java. This error indicates that you are trying to connect to a remote address and connection is refused remotely. It’s possible if there is no remote process/service listening at the specified address or port.

You might see one of the following error lines in your stack trace when you get Connection refused exception.

java.net.ConnectException: Connection refused exception clearly indicates that the program you are executing is trying to connect to server side but a successful connection cannot be established.

Possible Causes of java.net.ConnectException: Connection refused

1. Client is trying to connect wrong IP or port: This is a common reason when you get ConnectException. Sometimes applications running on the server side allocate different ports each time they are started. You can either configure the application on the server side, so that it uses fixed port, or you can change the client application, so that it connects to correct port.

2. Server is not running: This is also a possible reason for java.net.ConnectException.
You should check whether the server is open or not. It might be a database server, an application server or a custom server you have implemented. If you try to open a socket connection to a closed server, you will get a connection exception.

3. Server is open but it is not listening connections: This might be the case, for instance, when application server is up and running but an installed application is not started correctly. You should check admin console of your server to check the status of applications on the server. Sometimes application is started correctly but it isn’t listening the port, you are trying to connect.

4. Firewall is blocking connections to remote host: Firewall might be the problem if you cannot connect to server side. If a firewall is blocking connections to server, client application cannot open connection on the specified IP and port.

How To Resolve java.net.ConnectException: Connection refused exception

1. Check IP address and port: First step to resolve java.net.ConnectException is checking IP address and port. If IP address and port are correct, then you should follow the other steps below.

2. Ping the server IP address: You can use ping tool to test whether you can connect to server or not.

A successful ping response is as follows:

Ping response for an unsuccessful connection is as follows:

3. Try connecting the server with Telnet: You can use telnet application to simulate connection to the server. To use telnet type telnet on the command prompt. If telnet responds “Could not open connection to the host”, then you should investigate further for problems. Maybe, server is not running, or there might be a firewall issue.

Источник

java.net.ConnectException: Connection refused

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:

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.

java net connectexception connection refused connect что делать. Смотреть фото java net connectexception connection refused connect что делать. Смотреть картинку java net connectexception connection refused connect что делать. Картинка про java net connectexception connection refused connect что делать. Фото java net connectexception connection refused connect что делать

java net connectexception connection refused connect что делать. Смотреть фото java net connectexception connection refused connect что делать. Смотреть картинку java net connectexception connection refused connect что делать. Картинка про java net connectexception connection refused connect что делать. Фото java net connectexception connection refused connect что делать

17 Answers 17

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

java net connectexception connection refused connect что делать. Смотреть фото java net connectexception connection refused connect что делать. Смотреть картинку java net connectexception connection refused connect что делать. Картинка про java net connectexception connection refused connect что делать. Фото java net connectexception connection refused connect что делать

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.

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

Socket clientSocket = new Socket(«localhost», 5000);

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.

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

java net connectexception connection refused connect что делать. Смотреть фото java net connectexception connection refused connect что делать. Смотреть картинку java net connectexception connection refused connect что делать. Картинка про java net connectexception connection refused connect что делать. Фото java net connectexception connection refused connect что делать

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

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.

Источник

Handling java.net.ConnectException

Last modified: December 31, 2020

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

1. Introduction

In this quick tutorial, we’ll discuss some possible causes of java.net.ConnectException. Then, we’ll show how to check the connection with the help of two publicly available commands and a small Java example.

2. What Causes java.net.ConnectException

The java.net.ConnectException exception is one of the most common Java exceptions related to networking. We may encounter it when we’re establishing a TCP connection from a client application to a server. As it’s a checked exception, we should handle it properly in our code in a try-catch block.

There are many possible causes of this exception:

3. Catching the Exception Programmatically

We usually connect to the server programmatically using the java.net.Socket class. To establish a TCP connection, we must make sure we’re connecting to the correct host and port combination:

If the host and port combination is incorrect, Socket will throw a java.net.ConnectException. In our code example above, we print the stack trace to better determine what’s going wrong. No visible stack trace means that our code successfully connected to the server.

In this case, we should check the connection details before proceeding. We should also check that our firewall isn’t preventing the connection.

4. Checking Connections With the CLI

Through the CLI, we can use the ping command to check whether the server we’re trying to connect to is running.

For example, we can check if the Baeldung server is started:

If the Baeldung server is running, we should see information about sent and received packages.

telnet is another useful CLI tool that we can use to connect to a specified host or IP address. Additionally, we can also pass an exact port that we want to test. Otherwise, default port 23 will be used.

For example, if we want to connect to the Baeldung website on port 80, we can run:

It’s worth noting that ping and telnet commands may not always work — even if the server we’re trying to reach is running and we’re using the correct host and port combination. This is often the case in production systems, which are usually heavily secured to prevent unauthorized access. Besides, a firewall blocking specific internet traffic might be another cause of failure.

5. Conclusion

In this quick tutorial, we’ve discussed the common Java network exception, java.net.ConnectException.

We started with an explanation of possible causes of that exception. We showed how to catch the exception programmatically, along with two useful CLI commands that might help to determine the cause.

As always, the code shown in this article is available over on GitHub.

Источник

Java.net.ConnectException Connection timed out: no further information что делать

java net connectexception connection refused connect что делать. Смотреть фото java net connectexception connection refused connect что делать. Смотреть картинку java net connectexception connection refused connect что делать. Картинка про java net connectexception connection refused connect что делать. Фото java net connectexception connection refused connect что делать

java net connectexception connection refused connect что делать. Смотреть фото java net connectexception connection refused connect что делать. Смотреть картинку java net connectexception connection refused connect что делать. Картинка про java net connectexception connection refused connect что делать. Фото java net connectexception connection refused connect что делать

Minecraft — это одна из самых популярных серий игр для всех платформ. Именно ее простота и низкие системные требования позволяют играть практически в любом месте и на любом устройстве. Однако, постоянное подключение к сети создает массу проблем многим пользователям. Одной из ошибок становится «Java.net.ConnectException Connection timed out: no further information».

Причины ошибки подключения в Майнкрафт

Данный сбой возникает при попытке запустить игровую сессию на сервере. Плагин Java также может выходить из строя или просто требовать обновления. Другими источниками конфликта выступают: технические ремонты на сервере, окончание платного аккаунта, системные сбои с очередными установленными обновлениями, перебои в предоставлении интернета от провайдера, блокированный или серый ip-адрес.

java net connectexception connection refused connect что делать. Смотреть фото java net connectexception connection refused connect что делать. Смотреть картинку java net connectexception connection refused connect что делать. Картинка про java net connectexception connection refused connect что делать. Фото java net connectexception connection refused connect что делать

Ошибка «Java.net.ConnectException Connection timed out».

Как исправить ошибку «Connection timed out»

Все предложенные советы описаны с учетом того, что ваша операционная система имеет актуальные обновления, Java плагин последней версии.

Проблема со стороны сервера

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

Чаще всего стоит просто немного подождать и подключится спустя некоторое время.

Антивирус

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

java net connectexception connection refused connect что делать. Смотреть фото java net connectexception connection refused connect что делать. Смотреть картинку java net connectexception connection refused connect что делать. Картинка про java net connectexception connection refused connect что делать. Фото java net connectexception connection refused connect что делать

Отключение экрана антивируса.

Платные подписки

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

Оформите платную подписку заново или перейдите на бесплатные сервера.

Проблема в IP-адресе

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

java net connectexception connection refused connect что делать. Смотреть фото java net connectexception connection refused connect что делать. Смотреть картинку java net connectexception connection refused connect что делать. Картинка про java net connectexception connection refused connect что делать. Фото java net connectexception connection refused connect что делать

Локальная сеть Hamachi.

Актуальность версии

Minecraft постоянно выпускает разные версии. Если на сервере установлена одна версия, а у вас на компьютере другая, то избежать ошибки будет не возможно. Это актуально для всех игр с многопользовательскими режимами.

Скачайте и установите Майнкрафт той версии, которая требуется для вашего сервера.

Проблема из-за модов

Все стараются устанавливать как можно больше разных дополнений — модов, патчей и расширений. Однако, такие моды очень часто наполнены разными багами, которые в итоге приводят к системным ошибкам. Всегда отслеживайте разработчиков того или иного дополнения. Желательно инсталлировать популярные моды, используемые уже не один месяц другими игроками. Удалите последние моды. Переустановите в крайнем случае всю игру заново.

java net connectexception connection refused connect что делать. Смотреть фото java net connectexception connection refused connect что делать. Смотреть картинку java net connectexception connection refused connect что делать. Картинка про java net connectexception connection refused connect что делать. Фото java net connectexception connection refused connect что делать

Ошибка подключения к серверу Майнкрафт

Подобная ошибка «Connection refused» в Minecraft

Заключение

Данные советы должны подсказать, что делать для исправления ошибки «Java.net.ConnectException Connection timed out» в Майнкрафт. Обратите особое внимание на ваш ip-адрес и его смену. Если у вас есть свои решения, огромная просьба указать их в комментариях ниже.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *