我正在为我的类(class)开发一些对等 2 对等应用程序,有人告诉我让服务器发现彼此,他们必须多播到他们的 UDP 端口 1110 并收听他们的 UDP 端口 1110。我写了如下代码这样做。为了测试,我运行了 2 个发送和接收的服务器。但似乎没有任何效果。你认为我的问题在哪里?
我将 2 个服务器放在 2 个不同的文件夹中。我像这样为我的 NIC 分配了 IP 地址 ifconfig eth0:3 192.168.0.11 netmask 255.255.255.0 up
我应该如何告诉每台服务器新的 IP 地址?
广播监听器
class BroadcastListner implements Callable<Object> {
int PORT = 1110;
String IP = "255.255.255.255";
MulticastSocket socket ;
DatagramPacket packet;
InetAddress IPAD;
byte data[] = null ; //////////////change size
int numOfNodes;
BroadcastListner(String IP, int numOfNodes) {
try {
this.numOfNodes = numOfNodes;
this.IP = IP;
IPAD = InetAddress.getByName(IP);
socket = new MulticastSocket(PORT);
packet = new DatagramPacket(data,data.length);
} catch (Exception e) {
e.printStackTrace();
}
}
BroadcastListner(int numOfNodes) {
try{
this.numOfNodes = numOfNodes;
// this.IP = IP;
IPAD = InetAddress.getByName(IP);
socket = new MulticastSocket(PORT);
packet = new DatagramPacket(data,data.length);
} catch (Exception e) {
e.printStackTrace();
}
}
public String call() {
try{
socket.joinGroup(IPAD);
} catch (Exception e) {
e.printStackTrace();
return "";
}
while(true) {
try {
socket.receive(packet);
String str = new String(packet.getData());
System.out.println(" Time signal received from"+
packet.getAddress() + " Time is : " +str);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
//socket.leaveGroup(IPAD);
//socket.close();
//return "";
}
}
广播发送者
class BroadcastSender implements Callable<Object> {
int PORT = 1110;
String IP = "255.255.255.255";
MulticastSocket socket;
DatagramPacket packet;
InetAddress IPAD;
byte[] data = "IAmAServer".getBytes();
//int numOfNodes;
String str = "IAmAServer";
BroadcastSender(String IP) {
try {
// this.numOfNodes = numOfNodes;
this.IP = IP;
IPAD = InetAddress.getByName(IP);
socket = new MulticastSocket();
} catch (Exception e) {
e.printStackTrace();
}
}
BroadcastSender() {
try{
// this.numOfNodes = numOfNodes;
// this.IP = IP;
IPAD = InetAddress.getByName(IP);
socket = new MulticastSocket();
} catch (Exception e) {
e.printStackTrace();
}
}
public String call() {
try {
socket.joinGroup(IPAD);
socket.setTimeToLive(10);
} catch (Exception e) {
e.printStackTrace();
return "";
}
while(true) {
try {
Thread.sleep(2000);
packet = new DatagramPacket (data,str.length(),IPAD,PORT);
socket.send(packet);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
//return "";
}
}
最佳答案
你需要试试192.168.0.255这个广播地址
另一种方法是使用多播而不是广播地址,如 224.x.x.x,它不绑定(bind)到特定子网。
关于java - Java 中的多播不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9150830/