我们目前正在使用 Java 开发客户端-服务器游戏。我们使用 DatagramSocket
来执行客户端和服务器之间的通信。为了让客户端与服务器通信,他必须知道运行服务器的机器的 LAN ip 地址。多个客户端可以连接到服务器,我们为每个客户端使用一个线程。
我们的问题是我们想向客户端显示正在运行的服务器的 LAN ip 地址列表,以便他们更容易找到服务器,如 Counter Strike 中的 slist 命令。我们的解决方案是客户端向所有连接到网络的计算机发送一条消息,如果一台运行着服务器的计算机收到它,它将回复一条消息给客户端,然后我们在客户端打印它的 ip 地址。
InetAddress localHost = Inet4Address.getLocalHost();
String myIP=localHost.toString().substring(localHost.toString().lastIndexOf("/")+1);
//split myIP into 4 parts (part1.part2.part3.part4)
//use the first part to check the class of the network (A, B, or C)
//I'll skip to C
if(part1>=1 && part1<=126) //A
else if(part1>=128 && part1<=191) //B
else if(part1>=192 && part1<=223){
String network= part1 + "." + part2 + "." part3;
String guess;
for(i=0;i<255;i++){
guess = network+"."+i;
serverSend(guess); //send the message to an ip address in the network
}
}
对于 C 类网络,它工作正常,但对于 B 和 A,它太慢了。我们假设 B 和 A 的最坏情况子网掩码为 255.255.0.0(65,025 次迭代)和 255.0.0.0 (16,581,375)。
有人对此有更好的解决方案吗?提前谢谢你。
最佳答案
你要找的是广播。
我为你收集了一个教程: http://download.oracle.com/javase/tutorial/networking/datagrams/broadcasting.html
关于Java Lan Game list 运行服务器的IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7693838/