java.net.ConnectException – How to solve Connect Exception
In this example we are going to discuss about one of the most common exceptions you will come across when dealing with network programming in Java: ConnectException
. ConnectException
is a subclass of SocketException
, and that alone reveals that it is meant to inform you about an error that occurred when you tried to create or access a socket. To be more specific, ConnectException
is an exception that you will see in the client side of your application and it can emerge when a client fails to create a connection with a remote server socket.
1. A simple Client-Server program
Here is a very simple Client-Server program. It creates two threads. The first one, SimpleServer
, opens a socket on the local machine on port 3333
. Then it waits for a connection to come in. When it finally receives a connection, it creates an input stream out of it, and simply reads one line of text from the client that was connected. The second thread, SimpleClient
, attempts to connect to the server socket that SimpleServer
opened. When it does so, it sends a line of text and that’s it.
ConnectExceptionExample.java:
package com.javacodegeeks.core.net.connectexception; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; public class ConnectExceptionExample { public static void main(String[] args) { //new Thread(new SimpleServer()).start(); new Thread(new SimpleClient()).start(); } static class SimpleServer implements Runnable { @Override public void run() { ServerSocket serverSocket = null; while (true) { try { serverSocket = new ServerSocket(3333); Socket clientSocket = serverSocket.accept(); BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); System.out.println("Client said :"+inputReader.readLine()); } catch (IOException e) { e.printStackTrace(); }finally{ try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } } static class SimpleClient implements Runnable { @Override public void run() { Socket socket = null; try { Thread.sleep(3000); socket = new Socket("localhost", 3333); PrintWriter outWriter = new PrintWriter(socket.getOutputStream(),true); outWriter.println("Hello Mr. Server!"); } catch (InterruptedException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
As you can see, because I’m launching the two threads simultaneously, I’ve put a 3 second delay in SimpleClient
for the client to wait before attempting to connect to the server socket, so as to give some time to server thread to open the server socket.
If you run the above program, after 3 seconds you will see something like this :
Client said :Hello Mr. Server!
That means that the client, successfully connected to the server and achieved to transmit its text.
2. Simple cases of ConnectException
What happens if the client attempts to connect to localhost
, not in port 3333
that the server listens, but instead in port 1234
. To test that I will simply change line:
socket = new Socket("localhost", 3333);
to
socket = new Socket("localhost", 1234);
And run the program again.After 3 seconds, here’s what happens:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.(Socket.java:425)
at java.net.Socket.(Socket.java:208)
at com.javacodegeeks.core.net.connectexception.ConnectExceptionExample$SimpleClient.run(ConnectExceptionExample.java:65)
at java.lang.Thread.run(Thread.java:744)
So there, immediately, you have one occasion that can trigger a java.net.ConnectException
. The reason is that you, obviously trying to access a port on localhost
that is not open.
Other examples that also trigger a java.net.ConnectException
follow the same pattern more or less: You are attempting to make a connection on a remote socket and that connection is refused. The reason it’s refused can vary. In the above example, I’m trying to access a port on the local machine that simply doesn’t exist.
Let’s change:
socket = new Socket("localhost", 3333);
to
socket = new Socket("193.124.15.95", 3333);
Same thing happens:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.(Socket.java:425)
at java.net.Socket.(Socket.java:208)
at com.javacodegeeks.core.net.connectexception.ConnectExceptionExample$SimpleClient.run(ConnectExceptionExample.java:65)
at java.lang.Thread.run(Thread.java:744)
If you want to try this make sure, you put a valid existing IP address (or else you will get an UnknownHostException
). But the point is that again, we are trying to connect to a specific server to a specific port, but that port doesn’t exist of the server.
Another trivial example is to simply not start the server thread and just let the client run. You can change the IP and port values in the client to be in the “correct” configuration : socket = new Socket("localhost", 3333);
.
But don’t start the server thread:
public static void main(String[] args) { //new Thread(new SimpleServer()).start(); new Thread(new SimpleClient()).start(); }
The same thing happens:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.(Socket.java:425)
at java.net.Socket.(Socket.java:208)
at com.javacodegeeks.core.net.connectexception.ConnectExceptionExample$SimpleClient.run(ConnectExceptionExample.java:65)
at java.lang.Thread.run(Thread.java:744)
In this case the server was not running at all, even though the client used the correct configuration.
3. How to solve Connect Exception
Following the directives of the above paragraphs, there are one or two things that you can check when you come across a java.net.ConnectException
.
- Check the client configuration: That involves checking whether the client is trying to connect to the correct IP address and the correct port. For more complex connection, for example if you are trying to make an RMI (Remote Method Invocation) call, you should check if you are using the correct protocol, port and IP in the connection String. Same goes if you’re trying to connect to a MySQL server via JDBC.
- Check the server configuration: That involves checking whether the server can actually listen to the port that the client tries to connect to.
- Make sure that the server is up and running: Although all your configurations are fine, your server application might have crushed and stopped, and therefore it is down.
- Check if the remote client or server are connected to the net: You have to make sure that both machines are accessible in the network you are working on. Whether this is the same host (localhost), or your home network which means that both of the machines have to be connected to the same router (or be accessible by one another anyway), or it is a company network which means that both machines have to have access to he company network, or if its a completely remote connection then both machines have to have Internet access. In sum, make sure that the hosts that run your client and server application are accessible by one another.
- Check firewall configurations: This is a very common source of
java.net.ConnectException
. If you are trying to connect to a remote host that you know is running and you have all the configurations correct but you still get that exceptions, chances are that the remote server host blocks this port with a firewall. For example, it might only allow local connection to that port, but not remote connections. or might only allow specific IPs to connect to the port etc. Furthermore it is highly possible that your own network cannot allow that connection. For example if you stand behind your company network and you try to connect to a remote server, it is possible that your company’s router will block the connection.
Download Source Code
That’s it. That was a tutorial on java.net.ConnectException and tips on how to solve Connect Exception. You can download the source code of this example here : ConnectExceptionExample.zip
how to execute this ? it fails with below error:
ConnectExceptionExample/src/com/javacodegeeks/core/net/connectexception>java ConnectExceptionExample
Picked up _JAVA_OPTIONS: -Djava.security.egd=file:///dev/urandom -Duser.timezone=Asia/Tokyo
Error: Could not find or load main class ConnectExceptionExample
Yes , there was issue in credentials of database. As i changed the database credentials , application started working.