Java LAN游戏列表运行服务器的IP地址
我们目前正在用 Java 开发客户端-服务器游戏。我们使用DatagramSocket
来执行客户端和服务器之间的通信。为了让客户端能够与服务器进行通信,他必须知道运行服务器的计算机的 LAN IP 地址。多个客户端可以连接到服务器,我们为每个客户端使用一个线程。
我们的问题是我们想要向客户端显示正在运行的服务器的 LAN IP 地址列表,以便他们更容易找到服务器,就像《反恐精英》中的 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)。
有人对此有更好的解决方案吗?先感谢您。
We are currently working on a client-server game in java. We used DatagramSocket
to perform communications between client and server. Inorder for the client to communicate to server, he must know the LAN ip address of the machine where the server is running. Multiple clients can connect to server, we used a thread for each client.
Our problem is we wanted to show a list of LAN ip addresses of running servers to the clients so that it is easier for them to find servers like slist command in Counter Strike. Our solution is the client sends a message to all computers connected to the network and if a computer with a running server receives it, it will reply a message back to the client and then we print it's ip address in the client.
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
}
}
It works fine for network in class C but for B and A, it is too slow. We assume the worst-case subnet mask for B and A which is 255.255.0.0 (65,025 iterations) and 255.0.0.0 (16,581,375).
Does anyone got a better solution to this? thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在寻找的内容正在广播。
我为大家整理了一份教程:
http://download.oracle.com/javase/tutorial/networking/datagrams /广播.html
what you are looking for is broadcast.
I have gathered a tutorial for you:
http://download.oracle.com/javase/tutorial/networking/datagrams/broadcasting.html