The Java Client-Server application works only on the local network

advertisements

I made a simple java client-server application, where the client (android mobile) send messages to the server (pc), however both of them are connected to the same network. How can I do the same service through the internet instead of localhost? Using 3G at my mobile, for example. I tried using my public IP as well but it didn't work. My server is just like that:

    import java.io.*;
    import java.net.*;
    import java.util.Scanner;

    public class PCServer {

        public static void main(String[] args) throws IOException {

        ServerSocket server = new ServerSocket(5000);

        Socket client = server.accept();
        Scanner s = new Scanner(client.getInputStream());
        while (s.hasNextLine()) {
            System.out.println(s.nextLine());
        }

        s.close();
        server.close();
        client.close();
        }
    }


To access your localhost from outside of your network you have to do few things

  1. In Firewall: allow incoming connections on the port that your server listening for.
  2. In your local router: forward all inbound connections to the required port on to the IP of the local computer with the same port.
  3. Replace the localhost with your public IP in the client application.

Note: To make this solution usable you should have a static IP so you can rely on it and use it inside you client application.