0

我正在尝试通过 Internet 实现多播通信。这是我的代码

首先发送然后接收 5 次代码:

public static void main(String args[]) throws IOException
    {
        MulticastSocket socket = new MulticastSocket(4446);
        InetAddress group = InetAddress.getByName("228.5.6.7");
        socket.joinGroup(group);
        socket.setNetworkInterface(NetworkInterface.getByInetAddress(group));
        DatagramPacket packet;
        System.out.println("Trasmitter Started!!");
        for (int i = 0; i < 5; i++)
        {
            String buf = "Hi receiver";
            packet = new DatagramPacket(buf.getBytes(), buf.getBytes().length,group,4446);
            socket.send(packet);
            System.out.println("Packet Sent!");
            byte[] buff = new byte[256];
            packet = new DatagramPacket(buff,buff.length);
            socket.receive(packet);
            String received = new String(packet.getData());
            System.out.println("Quote of the Moment: " + received);
        }
        socket.leaveGroup(group);
        socket.close();
    }

只接收:

public static void main(String args[]) throws IOException
    {
        System.setProperty("java.net.preferIPv4Stack", "true");
        MulticastSocket socket = new MulticastSocket(4446);
        InetAddress group = InetAddress.getByName("228.5.6.7");
        //socket.setNetworkInterface(NetworkInterface.getByInetAddress(group));
        socket.setInterface(group);
        socket.joinGroup(group);

        DatagramPacket packet;
        System.out.println("Receiver Started!!");
        for (int i = 0; i < 5; i++)
        {
            byte[] buff = new byte[256];
            packet = new DatagramPacket(buff,buff.length);
            socket.receive(packet);
            String received = new String(packet.getData());
            System.out.println("Received Message: " + received);
        }
        socket.leaveGroup(group);
        socket.close();
    }

该代码在一台机器上工作,但是当我尝试在另一台机器上运行接收器时,它没有收到任何东西。我不知道我要去哪里错了?我搜索了一些解决方案,他们说将 networkInterface 添加到套接字,但这也不起作用。
操作系统:Windows 8.1
我也在使用代理(如果这可能是问题)

4

1 回答 1

0
socket.setNetworkInterface(...);

摆脱这条线。您将接口设置为组地址,这没有意义。我很惊讶它没有抛出异常。

于 2015-04-05T23:34:37.197 回答