Search code examples
javasocketstcpclient-server

Why I can't connect my sockets from two PCs in Java?


So far I have achieved making server/client relations on the same computer by parallelly running different java classes. As I don't want to overcomplicate this question, I will post my simplified code which works perfectly fine.

Server:

public class Server {
    public static final int PORT = 9090;

    public static void main (String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket (PORT);
            Socket client = serverSocket.accept ();
            System.out.println ("Client connected!");
        } catch (IOException ioException) {
            ioException.printStackTrace ();
        }
    }

}

Client:

public class Client {
        public static final int PORT = 9090;
        public static final String IP_ADDRESS = "127.0.0.1";

    public static void main (String[] args)  {
        try {
            Socket socket = new Socket (IP_ADDRESS,PORT);

        } catch (IOException ioException) {
            ioException.printStackTrace ();
        }
    }

}

After I run them, I get the expected output - console in class Server prints "Client connected!".

Like any other curious programmer, I decided to try out the same program on my two laptops. One laptop has client code, while second has server code. Of course, I had to change "127.0.0.1" or "localhost" to ip address my server laptop has by typing on google "what is my IP address". I just copied that new IP address into IP_ADDRESS variable and hoped it would work the same. Unfortunately, it didn't happen. My client laptop looks as if it never connected to server laptop, because server laptop never printed message "Client connected!". What am I missing? It looks so easy, yet it doesn't work. Could someone help me solve this?

P.S. I don't want to share my IP address due to privacy reasons, but it was the first number that pops when any of you google: what is my IP address?


Solution

  • If you are on a local network, you don't have to take your public IP. You need to find your local IP (if you are on linux, a simple "ip a" and you'll have your IP address, if you are on windows ) If you are not on a local network, you could open your router' settings to open the 9090 port but I STRONGLY discourage you to do something like that for security reason.