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?
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.
Send a discover message using either:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With