UDP组播的代码实现
UDP组播的代码实现
组播地址:224.0.0.0~239.225.225.225
其中224.0.0.0~224.0.0.225为预留的组播地址, 操作系统在用
组播的发送端
- 创建发送端的Socket对象(DatagramSocket)
- 创建数据,并把数据打包(DatagramPacket)
- 调用DatagramSocket对象的方法发送数据(单播中,这里是发送给指定ip的电脑,但是在组播中,这里是发给组播的地址)
InetAddress address = InetAddress.getByName("224.0.1.0");
- 释放资源
组播的接收端:
- 创建接收端的
MulticastSocket
对象MulticastSocket ms = new MulticastSocket(10086);
- 创建一个箱子,用于接收数据
DatagramPacket dp = new DatagramPacket(new byte[1024], 1024)
- 把当前的电脑添加到这个组中
ms.joinGroup(InetAddress.getByName("224.0.1.0"));
- 调用DatagramSocket的方法接收数据并将数据放入箱子中
- 解析数据包,并把数据在控制台显示
- 释放资源
public class ClientDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket();
String s = "hello 组播";
byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
InetAddress address = InetAddress.getByName("224.0.1.0");
int port = 10000;
DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address, port);
ds.send(dp);
ds.close();
}
}
// 接收端
public class ServerDemo {
public static void main(String[] args) throws IOException {
MulticastSocket ms = new MulticastSocket(10000);
DatagramPacket dp = new DatagramPacket(new byte[1024], 1024);
// 把当前计算机绑定一个组播地址,表示添加到这一组中
ms.joinGroup(InetAddress.getByName("224.0.1.0"));
ms.receive(dp);
byte[] data = dp.getData();
int length = dp.getLength();
System.out.println(new String(data, 0, length));
ms.close();
}
}