Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java network game: How to list available servers?

I'm working on a game that uses local area network. Like most of multiplayer games, there is a server-client system. Computer A runs an instance of program, creates a server and wait; Computer B do the same thing. Now Computer C runs the program, what I want is that he can see computer A and B listed there as game servers. How can I do this?
In order to list all of the servers available, a simple solution might be this: I need to check all of the IP addresses in a particular range and see if they respond via my specific port or not. If yes, therefor an instance of game is running on it and should be listed in the servers list.
Is the solution described above a good one? I've searched and get this piece of code:

public void checkHosts(String subnet){
    int timeout=1000;
    for (int i=1;i<254;i++){
        String host=subnet + "." + i;
            if (InetAddress.getByName(host).isReachable(timeout)){
                System.out.println(host + " is reachable");
            }
    }
}

but is takes so much time and is useless. If it's not the right solution, what are some other ways?

like image 749
mehrmoudi Avatar asked Mar 23 '12 13:03

mehrmoudi


2 Answers

If you are running on a local network, your method might take a huge amount of time and is definitely not the best solution.

You can solve it by having your servers periodically broadcast their addresses in the network, and have all the clients listen for it. A good example can be found in the Java Tutorials.

like image 68
Marcelo Avatar answered Sep 18 '22 05:09

Marcelo


Send a discover message using either:

  1. a multicast (use java.netMulticast socket)
  2. broadcast (use java.net.DatagramSocket) to the networks broadcast address

Have all servers listen for that and reply saying "I'm here" and possibly more information for further connection setup (server name, version, use port x, udp or tcp etc)

like image 23
Mattias Isegran Bergander Avatar answered Sep 18 '22 05:09

Mattias Isegran Bergander