0

I am trying to use sockets to connect to a server. I'm using Intellij IDEA and a JAVAFX project on Ubuntu. I am currently facing this error:

" Caused by: java.net.ConnectException: Connection refused"

The code that this error is pointing to is:

Socket serverSocket = new Socket("127.0.0.1", 8080);
        ConnectionHandler handler = new ConnectionHandler(serverSocket);
        String[] dirs = handler.receiveDirs();
        System.out.println(dirs[0]);

If someone can please help me out and tell me what possible problems there could be, and please let me know any possible fixes! Thanks!

newbdeveloper
  • 97
  • 2
  • 3
  • 12

2 Answers2

3

The possible reasons why you are getting that error are:

  • You do not have a Server program running.
  • You run the Client program first before the Server application.
  • Your port might be wrong or your IP is incorrect (assuming that your server is not located in the localhost).
  • Server might not want to establish connection as of the moment.

Safety measure check:

  • Try disabling the firewall first.
Enzokie
  • 7,365
  • 6
  • 33
  • 39
  • Hi I used the command "sudo ufw disable" on my terminal to disable firewall and still the same problem. Also, that IP is for localhost and default port should be 8080 right? – newbdeveloper Mar 29 '16 at 00:14
  • Another possibility is that the server is listening only on loopback (localhost) instead of all interfaces (which includes 127.0.0.1). – Paul Hicks Mar 29 '16 at 00:17
  • @PaulHicks , so i would I go upon fixing this? – newbdeveloper Mar 29 '16 at 00:20
  • My Tomcat uses port 8080 (You might have other program using this port), I assume you run the Server Socket program but it throws some conflict error because the port is already in use and you never notice it does not run at all and it seems the client socket can't actually find the server aside from that application occupying the port. – Enzokie Mar 29 '16 at 00:28
  • But if the server can run because another application has that port open, then the client won't get a Connection Refused exception, because that port is open. It will probably get another exception because there will be unexpected responses, but there won't be a connection refused. – Paul Hicks Mar 29 '16 at 00:43
  • So I changed the port to 80, and now the application runs, but with the a message in my output saying "HTTP/1.1 400 Bad Request". Before I wasn't even able to see my UI. – newbdeveloper Mar 29 '16 at 00:45
  • 'Server might not want to establish connection as of the moment' needs explaining. Firewalls don't cause this problem. @PaulHicks He is connecting to 127.0.0.1, which is localhost, and loopback. – user207421 Mar 29 '16 at 01:22
  • 127.0.0.1 is not _exactly_ the same as localhost or loopback. localhost (usually) has to be looked up via hostname or DNS, which can fail. And loopback is an interface address: if you have (for example) multiple ethernet cards, they all have loopback addresses, but at most one of them (and in modern OSes, probably none of them) will be the one that serves 127.0.0.1. And it is (slightly) relevant because it is possible to open the ServerSocket on one interface but open the client socket to 127.0.0.1 on another interface. Which would cause the observed problem. – Paul Hicks Mar 29 '16 at 01:29
1

You don't have anything running on your localhost at port 8080 for the socket to connect to. You can run a server such as Tomcat on that port, and then things should work.

Here is a standalone example that sets up a server socket to run locally (all it does is echo input from the client). Output will be "hello, jewelsea".

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ConnectToServer {
    public static void main(String[] args) throws IOException, InterruptedException {
        // server code.
        ServerSocket serverSocket = new ServerSocket(8082);
        Thread serverThread = new Thread(() -> {
            while(true) {
                try {
                    Socket connection = serverSocket.accept();

                    try (
                        BufferedReader serverReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        Writer serverWriter = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
                    ) {
                        serverWriter.write("hello, " + serverReader.readLine() + "\n");
                        serverWriter.flush();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Throwable t) {
                    t.printStackTrace();
                    throw t;
                }
            }
        });
        serverThread.setDaemon(true);
        serverThread.start();

        // client code.
        Socket clientSocket = new Socket("127.0.0.1", 8082);
        try (
            Writer clientWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
            BufferedReader clientReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        ) {
            clientWriter.write("jewelsea\n");
            clientWriter.flush();
            String response = clientReader.readLine();

            System.out.println(response);    
        }
    }
}

You might not want to work directly with sockets, but rather with higher level APIs, such as jax-rs.

jewelsea
  • 150,031
  • 14
  • 366
  • 406
  • A very nice example. For me, I this example where both client and server are being run within the same program works, but I still get connection refused when I try to use two separate programs for server and client. I guess windows is blocking the connection somehow. – CiaranWelsh Feb 17 '22 at 08:13
  • @CiaranWelsh perhaps you are trying to use a port < 1024, which is reserved and usually requires special privileges to use, or perhaps an internal firewall is blocking the access, or maybe you are trying to use a port which is already in use, or some other issue. If this app works for you using the hardcoded 8082 port, then running two separate processes for client and server should also work, as long as you are trying to run only one server on port 8082 at any one time. – jewelsea Feb 17 '22 at 11:26
  • @CiaranWelsh if you would like a tutorial in sockets, the [Oracle socket tutorial](https://docs.oracle.com/javase/tutorial/networking/sockets/index.html) is good. You could study the source for the knock knock example from the tutorial, copy it into a local project, compile and run it and it should provide you with a client and server running in separate processes. [GUI example for the knock knock app](https://stackoverflow.com/questions/70870998/how-to-return-objects-from-inputstream-client-to-a-javafx-controller/70888362#70888362). – jewelsea Feb 17 '22 at 11:28
  • Thanks for the advice, I'll do that ;-) – CiaranWelsh Feb 17 '22 at 12:32