java-With multicastSocket,收件人无法接收广播

时间:2017-05-10 08:24:47

标签: java

学习java MulticastSocket,同样的局域网只能在机器上接收广播,其他设备则不能。为什么?路由器设置问题或广播地址设置有问题吗? send.java

public class sentServer {
    public static void main(String[] args) {
        String host = "224.0.0.1";
        int port = 9998;String message = "test-multicastSocket";
        try {
            InetAddress group = InetAddress.getByName(host);
            MulticastSocket s = new MulticastSocket();
            s.joinGroup(group);
            DatagramPacket dp = new DatagramPacket(message.getBytes(),message.length(),group,port);
            s.send(dp);
            s.close();
        } catch (UnknownHostException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {e.printStackTrace();
        }
    }
}

此处设置的侦听地址为224.0.0.1

recevier.java

public class reClinet {
    public static void main(String[] args) {
        String host="224.0.0.1";
        int port=9998;
        int length=1024;
        byte[] buf=new byte[length];
        MulticastSocket ms=null;
        DatagramPacket dp=null;
        StringBuffer sbuf=new StringBuffer();
        try {
            ms=new MulticastSocket(port);
            dp=new DatagramPacket(buf,length);
            InetAddress group=InetAddress.getByName(host);
            ms.joinGroup(group);
            System.out.println("port is open");
            ms.receive(dp);
            ms.close();
            int i;
            for(i=0;i<1024;i++){
                if(buf[i]==0){
                    break;
                }
                sbuf.append((char)buf[i]);
            }
            System.out.println("message"+sbuf.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

` 感谢

1 个答案:

答案 0 :(得分:0)

如果您问:为什么只有连接到同一网段的系统才能看到广播?

这是Java中broadcasts性质:客户端连接到特定服务器;并加入广播组;那个客户端会收到通知。

如果客户没有收到这些通知;你必须调查你的网络设置,防火墙......