javatcplanwan

How to make a local multiplayer java game runs online?


I've developed a decent amount of multiplayer games lately in java (board/turn based games running on a tcp connection with data in/out streams) but they only work locally, I want to go a step further and make them run online, what do I need to change to make it work?

It seems like there are many ways to accomplish that yet i don't know where to start, as I don't know much about networking.

Besides that I don't have a real server, I'm only using my home router and my pc.

So here is what I've tried so far:

So the server side should be fine at least, my problem is with the client side, the client's socket won't connect to my public ip, when I searched for a solution I concluded that the client shouldn't be in the same LAN where the server is, so I used a mobile hotspot as a second network and tried again, but got the same results. (connection refused exception) is it because of the mobile hotspot (should I use another router) ? or is it just some coding tweaks ?

This is a minimal server class example

 public static void main(String[] args) {
    try {
        ServerSocket ss = new ServerSocket(50895);
        Socket cs = ss.accept();
        DataOutputStream out = new DataOutputStream(cs.getOutputStream());
        DataInputStream in = new DataInputStream(cs.getInputStream());
        out.writeInt(123456);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

And this a minimal client class example

public static void main(String[] args) {
    try {
        String ip = Inet4Address.getByName("my Dynamic IP address").getCanonicalHostName();
        System.out.println(ip);
        InetSocketAddress sa = new InetSocketAddress(ip, 50895);
        Socket cs = new Socket();
        cs.connect(sa);
        DataOutputStream out = new DataOutputStream(cs.getOutputStream());
        DataInputStream in = new DataInputStream(cs.getInputStream());
        System.out.println("received : " + in.readInt());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The method that i've tried always gives me a connection refused exception, so any solution would be appreciated.


Solution

  • I found a software solution to the problem through virtual lan (using LogMeIn Hamachi) which is basicly used for creating game servers, you just need to create an account and a network so your friends can join it, after that everything should be fine and runs as if it's locally hosted.

    You can download the software through here but there are many alternatives to choose from, that one gives you up to 5 people on the network for free, it's not the best, but still a free solution.

    I still want more of a java solution to this problem that doesn't require a third-party software.