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();
}
}
}
` 感谢
答案 0 :(得分:0)
如果您问:为什么只有连接到同一网段的系统才能看到广播?
这是Java中broadcasts的性质:客户端连接到特定服务器;并加入广播组;那个客户端会收到通知。
如果客户没有收到这些通知;你必须调查你的网络设置,防火墙......