Java ioexception connection refused connect

[Solved] java.net.ConnectException: Connection refused

Java is famous for networking applications. Java programmers have written socket programming for client server-based architecture. Most of the socket programming uses TCP-IP protocol for communication between client-server. Remote Method Invocation (RMI) also uses the TCP-IP protocol for communication. Sometime, it will generate java.net.ConnectException Connection refused exception for some communication channel error.

In this article, we will describe why this communication channel exception occurs in the first part, and in the second part, we will explain how to solve it.

1. Reasons for java.net.ConnectException

1. PORT or IP is incorrect: If PORT or IP is wrong, then the client will not be able to connect to the desired server. Then it will get this kind of exception.

2. Server is stopped: Suppose a server administration gave some IP address and PORT to you to access the server. But he stopped the server, but your client programs trying to access the server with administrator provided credentials, the client program will get the exception.

3. Protocol mismatch: We know that HTTP, RMI, Websocket, etc. uses TCP as the underlying protocol. HTTP request will start with http:// and RMI protocol starts with rmi// or WebSocket protocol start with ws://. If we request an HTTP request with rmi protocol, it will throw the java.net.ConnectException.

4. Server running in the different port: If server administrator provides you an IP and PORT but server running in a different port, it will give java.net.ConnectException Connection refused.

Читайте также:  Vs code версия python

5. Server or client is not in the network: If the client or server is disconnected from the network, then the client will not be able to find out the server. When the client program will not be able to find out the server, we will get this exception.

6. Firewall Restriction: In the networking world, many malware or virus programs can affect the network or personal computer that is connected to the public network. The different organizations put a firewall to the network to prevent this unwanted attack of various harmful products. Some companies allow internal networks only. If your server programs run on this network and the client IP is not allowed in this network, it will get the exception java.net.ConnectException Connection refused.

2. How to Solve this Exception:

The client can connect with the server easily when

a. The server is running in the IP and PORT provided by the server administrator.
b. There is no restriction on the network.
c. The client and server are on the network.

We have to check the above things first before connecting to the server. We can test this in different ways.

1. We can check the IP and PORT are available for the client by using telnet.

For example, you can use this command to check IP and PORT are running or not.

telnet javahungry.blogspot.com 80

2. We can check the IP is available for the client by pinging IP provided by the server administrator.
For example, you can ping with this command

ping javahungry.blogspot.com

You will get below result:

PING blogspot.l.googleusercontent.com (172.217.163.129): 56 data bytes 64 bytes from 172.217.163.129: icmp_seq=0 ttl=50 time=68.616 ms 64 bytes from 172.217.163.129: icmp_seq=1 ttl=50 time=66.957 ms 64 bytes from 172.217.163.129: icmp_seq=2 ttl=50 time=399.596 ms

3. Practical Example:

1. When we try to connect a database server like MYSQL or Oracle, but IP or PORT is not running or not accessible, then we get the exception java.net.ConnectException.
2. When a mail server is not running the desired PORT or IP, we will get this kind of exception.
3. When an application running in a different PORT or IP, but the client tries to connect, we will get this exception.

Example with Java Code

import java.net.*; import java.io.*; public class JavaHungry  public static void main(String[] args)  //Hostname is defined here String hostname = "127.0.0.1"; //PORT is defined here int port = 13; // If IP and PORT is invalid it will get exception try (Socket socket = new Socket(hostname, port))  // InputStream to read data from socket InputStream inputStream = socket.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); int data; StringBuilder outputString = new StringBuilder(); // Data read from input stream while ((data = inputStreamReader.read()) != -1)  outputString.append((char) data); > > catch (IOException ex)  // Exception will happen when scoket will not reachable System.out.println("Connection Refused Exception: " + ex); > > > 

If we execute the following command from the command line, we will get the desired exception

Connection Refused Exception: java.net.ConnectException: Connection refused (Connection refused)

4. Conclusion:

java.net.ConnectException is the general exception for invalid IP and PORT. We have to concern mainly with the valid IP and PORT and server status. If the server is running with the desired IP or PORT in the proper network, then a client can easily overcome this kind of exception.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry

Источник

Ошибка java.net.ConnectException: Connection refused – как исправить?

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

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

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

Причины

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

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

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

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

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

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

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

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

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

Java Network Programming

Как решить java.net.ConnectException: соединение отказано

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

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

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

Средняя оценка 1.5 / 5. Количество голосов: 33

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Видим, что вы не нашли ответ на свой вопрос.

Напишите комментарий, что можно добавить к статье, какой информации не хватает.

Источник

Оцените статью