嗨,我正在尝试 java 多播。
我在 - 10.0.0.1(网关)有一个 WIFI 路由器
和两个节点:
节点_1 - 10.0.0.4 节点_2 - 10.0.0.3
我的 IP 多播发件人如下所示:
private static class Sender extends Thread
{
// Create the socket but we don't bind it as we are only going to send data
private MulticastSocket s;
private static int senderPort = 15000;
private static String group = "225.4.5.6";
public Sender() throws IOException
{
s = new MulticastSocket(senderPort);
s.setInterface(InetAddress.getLocalHost());
s.joinGroup(InetAddress.getByName(group));
}
@Override
public void run() {
Integer data = 1;
while(true)
{
try {
s.send(new DatagramPacket(data.toString().getBytes(), data.toString().getBytes().length, InetAddress.getByName(group), senderPort));
Thread.sleep(3000);
data++;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
System.out.println("Sender - UnknownHostException");
}catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Sender - IOException");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
我的 IP 多播接收器看起来像:
private static class Receiver extends Thread
{
private MulticastSocket s;
private static int receiverPort = 15000;
private static String group = "225.4.5.6";
public Receiver() throws IOException
{
s = new MulticastSocket(receiverPort);
s.setInterface(InetAddress.getLocalHost());
s.joinGroup(InetAddress.getByName(group));
}
@Override
public void run() {
while (true)
{
byte buf[] = new byte[1024];
DatagramPacket pack = new DatagramPacket(buf, buf.length);
try {
System.out.println("Receiver waiting for data");
s.receive(pack);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.write(pack.getData(),0,pack.getLength());
System.out.println();
}
}
}
当我在同一个节点中同时拥有发送者和接收者时,它可以工作,但是当我将它们放在不同的节点中时,它就不起作用了。
我在这里想念什么?