UDP广播的代码实现
UDP广播的代码实现
广播的发送端:
- 创建发送端的DatagramSocket对象
- 创建数据,并把数据打包(DatagramPacket)
- 调用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("255.255.255.255");
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 {
DatagramSocket ds = new DatagramSocket(10000);
DatagramPacket dp = new DatagramPacket(new byte[1024], 1024);
ds.receive(dp);
byte[] data = dp.getData();
int length = dp.getLength();
System.out.println(new String(data, 0, length));
ds.close();
}
}