如何在java中监听多播消息?

时间:2015-05-24 10:47:05

标签: java network-programming broadcast

我正在做oracle关于向多个收件人广播的教程,但我收到了客户端的错误。 正如oracle的例子所述,我有我的客户端代码

public static void main(String[] args) throws IOException {
    MulticastSocket socket = new MulticastSocket(4446);
    InetAddress group = InetAddress.getByName("203.0.113.0");
    socket.joinGroup(group);

    DatagramPacket packet;
    for (int i = 0; i < 5; i++) {
        byte[] buf = new byte[256];
        packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet);

        String received = new String(packet.getData());
        System.out.println("Quote of the Moment: " + received);
    }

    socket.leaveGroup(group);
    socket.close();
}

引发异常

Exception in thread "main" java.net.SocketException: Not a multicast address
    at java.net.MulticastSocket.joinGroup(MulticastSocket.java:310)
    at BroadcastListener.main(BroadcastListener.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

怎么了?

1 个答案:

答案 0 :(得分:0)

多播IP地址必须以224 ..开头,符合RFC 5771。

来自维基百科:

  

IPv4多播地址由前导地址位定义   1110,源于早期的有类网络设计   当这组地址被指定为D类时,互联网   该组的无类别域间路由(CIDR)前缀是   224.0.0.0/4。