205

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
  • 2,950
  • 2
  • 21
  • 43
Samantha Catania
  • 4,516
  • 5
  • 36
  • 61
  • Can you please post the client code? If it is a remote client make sure you don't have any firewall issues! – home Jul 29 '11 at 16:40
  • I turned off firewalls on both client & server & still same problem – Samantha Catania Jul 29 '11 at 16:44
  • 2
    What interface is the server listening on. If you are only listening on localhost, you cannot connect remotely. – Thorbjørn Ravn Andersen Jul 29 '11 at 16:44
  • I was trying to connect remotely while using localhost, face palm. This is my first trial with TCP >.< How do I make it work remotely? – Samantha Catania Jul 29 '11 at 16:50
  • Remember that you may have some 'bare metal' hardware firewalls in between as well... does it work if client and server are on the same box? – home Jul 29 '11 at 16:51
  • same box as in same machine? If so yes – Samantha Catania Jul 29 '11 at 16:53
  • Server Fault has a canonical question about [Connection Refused](http://serverfault.com/questions/725262/what-causes-the-connection-refused-message). – Raedwald Sep 30 '15 at 12:33
  • I tried your code out and I didn't have any problems on my machine. it has to be something blocking your connection or else you are starting them in the wrong order. Are you making sure that your server isn't getting closed when you start the client up. My process was this. put both class file in one directory, then opened 2 command prompts to that directory to execute them separately. if your using an IDE it may be closing the server automatically which is why i recommend doing it this way – S E Jul 29 '11 at 17:50

16 Answers16

349

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_
  • 13,042
  • 6
  • 71
  • 81
Collin Price
  • 4,990
  • 2
  • 32
  • 35
  • 62
    I feel dumb for having overlooked the `You have not started your server`, but it was indeed the problem for me! – Alexis Leclerc Oct 22 '14 at 16:19
  • Just to make the point clear - "Java core is just fine". Only problem is we overlook issues.. (server state, ipaddress, port, internet connectivity - being on the same router is must for local IP's and more) – Vinay Bhargav Aug 11 '15 at 04:10
  • 1
    Collin, what exactly do you mean by 'the server is not waiting to accept connections'? People are parroting this around as though it means something. – user207421 Oct 08 '15 at 12:20
  • I wrote this a while ago but I think I meant it as another way of saying you have not started your server. – Collin Price Oct 09 '15 at 12:58
  • in my case I had four Gennymotion simulators running and I was trying to load the app on Galaxy tab and I was getting this error. after reading a lot from the buddy WEB, I then closed out all the simulators and eclipse, killed the ADP in the task manager and then restarted the Eclipse and everything is started working properly. I think when you have multiple simulators running and then you try to connect device, the ADB goes nuts in my experience. those are my two cents... :) – Vincy Oct 22 '15 at 12:02
  • I am getting this exception while trying to connect to a soap service. `java.util.concurrent.ExecutionException: java.net.ConnectException: https://services.xxxxxxxxx.com/xxxxxxxxxv2/Service.svc/soap`. It is not connection refused or timed out. It just prints out the address of the API and blows up. I have no idea whats causing this. – An Illusion Jun 15 '16 at 15:25
  • In case you are spring boot < 1.4, check if you activated WebIntegrationTest ... did the trick for me – Jan Galinski Feb 01 '17 at 12:31
  • @Sabarish Kumaran.V Your edit was (a) irrelevant and (b) wrong. Don't do that. – user207421 Mar 11 '17 at 11:17
  • @CollinPrice when app closed by clear ram, for the next time I got connection refused. do you have any idea? – MHSFisher Apr 25 '18 at 11:37
43

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.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
  • I get this exception sometimes. This happens for a particular period of time. It immediately throws this exception. And then everything becomes fine. I have a firewall in the server. But I have added an inbound rule to allow incoming connections on port 8080. Is the rule ignored sometimes? – Ashwin Sep 30 '12 at 16:25
  • @Ashwin: It's impossible to say, really - you'd need to work out exactly how far the data's getting. Look at your firewall logs etc. – Jon Skeet Sep 30 '12 at 17:53
  • @JonSkeet how to config our firewall if we have this error? – Nikhil Pareek Jan 19 '18 at 12:08
  • 1
    @Nikhil: I'm not qualified to answer that, but I suspect anyone who *is* qualified would need a lot more information to be able to help you. (For one thing, we don't know what firewall you have...) – Jon Skeet Jan 19 '18 at 14:58
7

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

Dao Lam
  • 2,493
  • 10
  • 33
  • 41
  • 4
    Of course you have to run the server before the client. Running the client first and trying to connect to the server means you're connecting to nothing when you fire up your server. – user3308043 Jun 12 '14 at 08:17
  • 5
    @user3308043 Yes it was obvious but it wasn't too obvious for some new programmers (like myself 3 years ago) so I just wanted to share it with those fellows who were clueless like me. – Dao Lam Oct 23 '15 at 18:51
  • Thanks, it also helped me, the test connection was succesfull but couldn't show any tables data. – Damien Christophe Aug 13 '19 at 07:52
7

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
  • 289,834
  • 37
  • 266
  • 440
home
  • 12,169
  • 5
  • 42
  • 54
  • I assume she is running them both on the same machine for testing purposes which is why localhost would be fine to use – S E Jul 29 '11 at 18:22
  • @Aaron: She said it works if client and server run on the same machine (you can find the answer in another comment). – home Jul 29 '11 at 19:21
  • 'The above row binds the socket to localhost' No it doesn't, it binds it to INADDR_ANY. That allows it to accept connections via any NIC. What the OP is doing is already correct. Answer is completely incorrect. Downvoting. – user207421 Jul 30 '11 at 02:21
  • @EJP: You're right with the `ServerSocket`, I modified the answer. Nevertheless, the `clientSocket` still tries to connect to `localhost`. – home Jul 30 '11 at 03:34
  • @home You need to *remove* the phrase about the bind address. – user207421 Jul 30 '11 at 08:11
  • @home bind() binds the socket to a local NIC and port. connect() connects you to a remote IP:port. They are completely different operations. – user207421 Jul 31 '11 at 02:36
6

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)

eRaisedToX
  • 2,783
  • 1
  • 18
  • 26
4

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

MrOnyancha
  • 597
  • 4
  • 23
  • 1
    This saved my day, but since vernemq does not install with apt-get, some people will need this link: https://vernemq.com/docs/installation/debian_and_ubuntu.html – 3xCh1_23 Sep 16 '16 at 13:37
2

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.

phoenix
  • 887
  • 3
  • 13
  • 36
1

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
  • 289,834
  • 37
  • 266
  • 440
Basheer AL-MOMANI
  • 11,997
  • 8
  • 79
  • 85
1

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)

Zhyano
  • 349
  • 3
  • 13
1

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)

user1419243
  • 1,427
  • 1
  • 17
  • 27
0

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();

    }
}
Santosh Karna
  • 99
  • 1
  • 6
  • 12
  • 1
    Not closing the client socket does not cause a connection refusal. There wouldn't *be* a client socket to close if the connection had been refused. – user207421 Jan 31 '18 at 12:22
0

I changed my DNS network and it fixed the problem

Eli Nb
  • 16
  • 2
0

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

syclone
  • 27
  • 10
0

Change local host to your ip address

 localhost
 //to you local ip
 192.168.xxxx
Gabriel Rogath
  • 431
  • 1
  • 3
  • 12
-2

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

Michael Munsey
  • 3,164
  • 1
  • 22
  • 14
-2

I had the same issue, and it turned out to be due to permission of the catalina.out file not being correct. It was not writable by the tomcat user. Once I fixed the permissions, the issue got resolved. I got to know that it is a permissions issue from the logs in the tomcat8-initd.log file:

/usr/sbin/tomcat8: line 40: /usr/share/tomcat8/logs/catalina.out: Permission denied

kbsbng
  • 1,967
  • 2
  • 16
  • 22
  • 1
    'Permission denied' is not the same thing as 'connection refused'. – user207421 Mar 21 '19 at 09:37
  • The Permission denied error was in the `tomcat8-initd.log` file while the server output logs had exactly the error mentioned in the question. – kbsbng Apr 13 '20 at 15:11