编写一个广播数据报程序。具体的,自定义一个组播地址及端口号,广播端每隔5秒发送当前的时间;定义一个接收端接收广播端发送的数据,并将收到的数据显示在命令行窗口中。Java
时间: 2024-03-02 10:48:58 浏览: 113
以下是一个简单的Java程序,实现了广播数据报的发送和接收。请注意,该程序仅用于演示目的,实际应用中需要进行更多的错误处理和异常处理。
广播端:
```java
import java.net.*;
import java.util.*;
public class BroadcastSender {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
InetAddress group = InetAddress.getByName("230.0.0.1");
int port = 8888;
while (true) {
String time = new Date().toString();
byte[] data = time.getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length, group, port);
socket.send(packet);
System.out.println("广播时间:" + time);
Thread.sleep(5000);
}
}
}
```
接收端:
```java
import java.net.*;
public class BroadcastReceiver {
public static void main(String[] args) throws Exception {
MulticastSocket socket = new MulticastSocket(8888);
InetAddress group = InetAddress.getByName("230.0.0.1");
socket.joinGroup(group);
byte[] buffer = new byte[1024];
while (true) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println("收到广播:" + message);
}
}
}
```
在终端中,先运行接收端BroadcastReceiver,然后再运行广播端BroadcastSender。程序输出结果如下:
```
收到广播:Tue Jun 22 22:20:03 CST 2021
收到广播:Tue Jun 22 22:20:08 CST 2021
收到广播:Tue Jun 22 22:20:13 CST 2021
...
```
阅读全文