当发送方和接收方在不同节点上时,Java IP多播问题

时间:2014-03-24 00:20:31

标签: java networking network-programming multicastsocket

您好我正在尝试java多播。

我有一个WIFI路由器 - 10.0.0.1(网关)

和两个节点:

Node_1 - 10.0.0.4 Node_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();
        }
    }
}

当我在同一节点中同时拥有发件人和接收者时,它会工作,但是当我将它们放在不同的节点中时,它不起作用。

我在这里失踪的是什么?

1 个答案:

答案 0 :(得分:0)

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

删除它。