import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
String s="通知:四至六周星期六上午网络编程上机";
int port=8001;//有时候有空指针的问题就是端口号和下面的地址不可以使用
InetAddress ia=null;
MulticastSocket ms=null;
public MultiServer()
{
try{
ms=new MulticastSocket(port);
ia=InetAddress.getByName("239.7.8.9");
ms.setTimeToLive(1);//设置组播套接字发送数据报范围为本地连接
ms.joinGroup(ia);//加入多组播
}catch(IOException e){
e.printStackTrace();
}
}
public void run()
{
while(true){
try {
DatagramPacket packet=null;
byte data[]=s.getBytes();
packet=new DatagramPacket(data,data.length,ia,port);
ms.send(packet);
sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new MultiServer().start();
}
在客户端:
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class MultiClient{
public void service(){
try{
MulticastSocket ms=new MulticastSocket(8001);
InetAddress ia=InetAddress.getByName("239.7.8.9");
ms.joinGroup(ia);
byte[] buffer=new byte[8192];
while(true){
DatagramPacket packet=new DatagramPacket(buffer,buffer.length);
ms.receive(packet);
String s=new String(packet.getData(),"UTF-8");
System.out.println(s);
}
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
new MultiClient().service();
}