0

嗨,我正在尝试 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();
        }
    }
}

当我在同一个节点中同时拥有发送者和接收者时,它可以工作,但是当我将它们放在不同的节点中时,它就不起作用了。

我在这里想念什么?

4

1 回答 1

0

通过调用 setInterface() 到本地主机,您可以防止 joinGroup() 消息离开当前主机。这在发送者中无关紧要,因为发送者无论如何都不必加入组,但在接收者中它将阻止其他主机、路由器等知道接收主机在组中。

只需将其删除。

于 2014-03-24T02:30:14.060 回答