[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.
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
Русские Блоги
Предпосылки: некоторые операторы HQL в бизнесе должны быть предварительно обработаны в проекте, поэтому в процессе анализа операторов HQL необходимо иметь возможность динамически изучать информацию об определенных классах сущностей в соответствии с механизмом отражения Java. Например: из Person, имя которого похоже на «% %», мы должны попытаться загрузить соответствующий класс сущности в соответствии с Person.
Подумав об этом, лучше, чтобы наша собственная система могла справиться с этим, прежде чем передать файлы конфигурации * .hbm.xml в SpringSessionFactoryBean Spring, чтобы кэшировать некоторую информацию о конфигурации для быстрого доступа при необходимости.
Первое, что нужно решить, это то, что bean-компонент, который настраивает SessionFactory весной, не может быть определен следующим образом:
com/neuqsoft/czgs/common/entity/Demo.hbm.xml com/neuqsoft/czgs/common/entity/PERSON.hbm.xml ……
Причина в том, что если мы определим это таким образом, наша система не сможет перехватить файлы ресурсов файла конфигурации сущностей. Чтобы решить эту проблему, я естественным образом подумал об интерфейсе FactoryBean весной, поэтому появились следующие классы.
public class HibernateMappingResourceFactoryBean implements FactoryBean < private List _list; public Object getObject() throws Exception < return _list; >public Class getObjectType() < return List.class; >public boolean isSingleton() < return true; >public void set_list(List _list) < this._list = _list; EntityManager.getInstance().registerAll(_list); >>
Он имеет две функции: одна для настройки bean-компонента экземпляра List, а другая — для регистрации всех файлов ресурсов в List в EntityManager. Мы упомянем его роль позже в EntityManager.
Следует отметить, что с помощью Spring можно легко внедрить атрибут типа List (через элемент list) в bean-компонент, но он не может просто настроить Bean-объект типа List, поэтому мы используем интерфейс FactoryBean и элемент list для Для достижения цели настройки bean-объекта типа List.
Фрагменты конфигурации HibernateMappingResourceFactoryBean и LocalSessionFactoryBean весной выглядят следующим образом.
com/neuqsoft/czgs/common/entity/Demo.hbm.xml com/neuqsoft/czgs/common/entity/PERSON.hbm.xml ……
Таким образом, это не мешает LocalSessionFactoryBean в Spring загружать файлы конфигурации Hibernate, а также не мешает нашей собственной системе загружать эти файлы конфигурации, и конфигурация относительно проста.
Но потом я столкнулся с проблемами в процессе синтаксического анализа XML. Я всегда сообщаю java.net.ConnectException: истекло время ожидания соединения: ошибка соединения. Я уверен, что это вызвано сетевым соединением. Наша компания не может выйти в Интернет в рабочее время. Вопрос в том, какое отношение парсинг XML-файлов имеет к сетевым соединениям?
Чтобы выяснить причину ошибки, необходимо проверить исходный код. Ниже приведен исходный код метода registerAll в классе EntityManager (до изменения).
public void registerAll(List resourceList)< if(resourceList!=null)< try< DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); DocumentBuilder builder=factory.newDocumentBuilder(); for(int i=0;icatch(Exception e) < throw new RuntimeException("Error:"+resourcePath,e); >> >catch(ParserConfigurationException e) < e.printStackTrace(); >catch (FactoryConfigurationError e) < e.printStackTrace(); >> >
Ошибка от org.w3c.dom.Document w3cDocument = builder.parse (is); Эта строка, несомненно, является ошибкой при разборе XML. Чтобы полностью понять причину ошибки, я открываю файл конфигурации сущности (Demo.hbm .xml) присмотрелся и обнаружил, что в определении типа документа действительно есть URL:
Поэтому я предполагаю, что синтаксический анализатор XML обнаружит, что системный идентификатор в определении типа документа является URL-адресом при синтаксическом анализе XML, а затем попытается установить соединение для чтения содержимого DTD через соединение. Если это так, подождите до окончания работы. Когда Интернет будет доступен, эта проблема должна исчезнуть. По совпадению, сейчас самое время выйти из работы, поэтому я начал перезагружать сервер. Все было ожидаемо, и ошибка исчезла.
Теперь вопрос заключается в том, как это сделать на работе. Существует ли механизм, который может изменить поведение анализатора XML по умолчанию при анализе определения типа документа? Ответ — да, то есть настроить анализатор сущностей для изменения его поведения по умолчанию. Сначала я скопировал определение типа документа Hibernate hibernate-mapping-3.0.dtd в путь классов нашего проекта. Затем я изменил метод registerAll в EntityManager следующим образом: Когда я начинаю работу, сервер не будет отчитываться в сети. Это ужасная ошибка соединения.
public void registerAll(List resourceList) < if(resourceList!=null)< try< DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); DocumentBuilder builder=factory.newDocumentBuilder(); builder.setEntityResolver(new EntityResolver()< public InputSource resolveEntity(String publicID, String systemID) throws SAXException, IOException < InputStream is=getClass().getResourceAsStream("hibernate-mapping-3.0.dtd"); return new InputSource(is); >>); for(int i=0;icatch(Exception e) < throw new RuntimeException("Error:"+resourcePath,e); >> >catch(ParserConfigurationException e) < e.printStackTrace(); >catch (FactoryConfigurationError e) < e.printStackTrace(); >> >
Connect Exception Class
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Signals that an error occurred while attempting to connect a socket to a remote address and port.
[Android.Runtime.Register("java/net/ConnectException", DoNotGenerateAcw=true)] public class ConnectException : Java.Net.SocketException
[] type ConnectException = class inherit SocketException
Remarks
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
Constructors
Construct a new ConnectException with no detailed message.
A constructor used when creating managed representations of JNI objects; called by the runtime.
Constructs a new ConnectException with the specified detail message as to why the connect error occurred.
Fields
Properties
Returns the cause of this throwable or null if the cause is nonexistent or unknown.
The handle to the underlying Android instance.
Creates a localized description of this throwable.
Returns the detail message string of this throwable.
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
Methods
Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.
Fills in the execution stack trace.
Provides programmatic access to the stack trace information printed by #printStackTrace() .
Returns an array containing all of the exceptions that were suppressed, typically by the try -with-resources statement, in order to deliver this exception.
Initializes the cause of this throwable to the specified value.
Prints this throwable and its backtrace to the standard error stream.
Prints this throwable and its backtrace to the specified print stream.
Prints this throwable and its backtrace to the specified print writer.
Sets the stack trace elements that will be returned by #getStackTrace() and printed by #printStackTrace() and related methods.
Explicit Interface Implementations
IJavaPeerable.Disposed() | (Inherited from Throwable) |
IJavaPeerable.DisposeUnlessReferenced() | (Inherited from Throwable) |
IJavaPeerable.Finalized() | (Inherited from Throwable) |
IJavaPeerable.JniManagedPeerState | (Inherited from Throwable) |
IJavaPeerable.SetJniIdentityHashCode(Int32) | (Inherited from Throwable) |
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) | (Inherited from Throwable) |
IJavaPeerable.SetPeerReference(JniObjectReference) | (Inherited from Throwable) |
Extension Methods
Performs an Android runtime-checked type conversion.